CodeIgniter 4 MongoDB CRUD Example

Table of Contents

Introduction

In this example I am going to build CodeIgniter 4 MongoDB CRUD example. CRUD is an acronym and stands for Create, Read, Update and Delete operations. SO, here I am going to fetch record(s) from MongoDB NoSQL database, creating a new record and storing into MongoDB collection, updating the existing record and deleting the existing record.

MongoDB is one of the widely used NoSQL(Not only SQL) database in market today. MongoDB is a document database with the scalability and flexibility that you want with the querying and indexing that you need. Often you come across a situation where you end up using MongoDB with PHP based framework Codeigniter 4.

Related Post:

codeigniter 4 mongodb crud

Prerequisites

PHP 7.4.22, CodeIgniter 4.1.6, MongoDB 5.0.5 (or 4+), Apache HTTP Server (Optional)

PHP and MongoDB Configurations

Project Directory

It’s assumed that you have setup PHP and CodeIgniter in Windows system.

Now I will create a project root directory called codeigniter-mongodb-crud.

Now move all the directories and files from CodeIgniter framework into the project root directory.

I may not mention the project root directory in subsequent sections and I will assume that I am talking with respect to the project root directory.

CRUD Application using CodeIgniter 4 and MongoDB

Now I will show you how to build CRUD application using MongoDB NoSQL database and CodeIgniter framework.

MongoDB Config

As a first step I want to declare some variables for MongoDB configurations.

The variables are declared into a config file app/Config/MongoDbConfig.php. You may want to read how to create custom config file in CodeIgniter 4.

<?php
 
namespace Config;
 
use CodeIgniter\Config\BaseConfig;
 
/**
* Author: https://roytuts.com
*/
 
class MongoDbConfig extends BaseConfig {
             
    public $host = 'localhost';
    public $port = 27017;
    public $username = '';
    public $password = '';
    public $authRequired = false;
 
}

MongoDB Library

I am creating a custom library to build a MongoDB database connection and the same connection will be used to perform database operations.

The following code is written into a file app/libraries/MongoDb.php file.

<?php
 
namespace App\Libraries;


/**
* Author: https://roytuts.com
*/
 
class MongoDB {
             
	private $conn;

	function __construct() {
		$config = new \Config\MongoDbConfig();

		$host = $config->host;
		$port = $config->port;
		$username = $config->username;
		$password = $config->password;
		$authRequired = $config->authRequired;

		try {
			if($authRequired === true) {
				$this->conn = new \MongoDB\Driver\Manager('mongodb://' . $username . ':' . $password . '@' . $host. ':' . $port);
			} else {
				$this->conn = new \MongoDB\Driver\Manager('mongodb://' . $host. ':' . $port);
			}
		} catch(MongoDB\Driver\Exception\MongoConnectionException $ex) {
			show_error('Couldn\'t connect to mongodb: ' . $ex->getMessage(), 500);
		}
	}

	function getConn() {
		return $this->conn;
	}
             
}

Model Class

The model class is responsible for performing database operations into MongoDB through CodeIgniter framework. Here, I am fetching data from MongoDB, inserting data into MongoDB, updating data into MongoDB and deleting data from MongoDB.

The model code is written into app/Models/UserModel.php file.

<?php

namespace App\Models;

use App\Libraries\MongoDb;

class UserModel {

	private $database = 'roytuts';
	private $collection = 'user';
	private $conn;

	function __construct() {
		$mongodb = new MongoDb();
		$this->conn = $mongodb->getConn();
	}

	function get_user_list() {
		try {
			$filter = [];
			$query = new \MongoDB\Driver\Query($filter);

			$result = $this->conn->executeQuery($this->database . '.' . $this->collection, $query);
			
			return $result->toArray();
		} catch(\MongoDB\Driver\Exception\RuntimeException $ex) {
			show_error('Error while fetching users: ' . $ex->getMessage(), 500);
		}
	}

	function get_user($_id) {
		try {
			$filter = ['_id' => new \MongoDB\BSON\ObjectId($_id)];
			$query = new \MongoDB\Driver\Query($filter);

			$result = $this->conn->executeQuery($this->database.'.'.$this->collection, $query);

			foreach($result as $user) {
				return $user;
			}

			return null;
		} catch(\MongoDB\Driver\Exception\RuntimeException $ex) {
			show_error('Error while fetching user: ' . $ex->getMessage(), 500);
		}
	}

	function create_user($name, $email) {
		try {
			$user = array(
				'name' => $name,
				'email' => $email
			);

			$query = new \MongoDB\Driver\BulkWrite();
			$query->insert($user);

			$result = $this->conn->executeBulkWrite($this->database.'.'.$this->collection, $query);

			if($result->getInsertedCount() == 1) {
				return true;
			}

			return false;
		} catch(\MongoDB\Driver\Exception\RuntimeException $ex) {
			show_error('Error while saving users: ' . $ex->getMessage(), 500);
		}
	}

	function update_user($_id, $name, $email) {
		try {
			$query = new \MongoDB\Driver\BulkWrite();
			$query->update(['_id' => new \MongoDB\BSON\ObjectId($_id)], ['$set' => array('name' => $name, 'email' => $email)]);

			$result = $this->conn->executeBulkWrite($this->database . '.' . $this->collection, $query);

			if($result->getModifiedCount()) {
				return true;
			}

			return false;
		} catch(\MongoDB\Driver\Exception\RuntimeException $ex) {
			show_error('Error while updating users: ' . $ex->getMessage(), 500);
		}
	}

	function delete_user($_id) {
		try {
			$query = new \MongoDB\Driver\BulkWrite();
			$query->delete(['_id' => new \MongoDB\BSON\ObjectId($_id)]);

			$result = $this->conn->executeBulkWrite($this->database . '.' . $this->collection, $query);

			if($result->getDeletedCount() == 1) {
				return true;
			}

			return false;
		} catch(\MongoDB\Driver\Exception\RuntimeException $ex) {
			show_error('Error while deleting users: ' . $ex->getMessage(), 500);
		}
	}

}

Controller Class

The controller class is responsible for handling clients’ requests and responses. The controller functions validates the input data coming from the end users before doing some operations.

The CRUD functions interacts with model class to perform the required actions.

The following code is written into a file app/Controllers/UserController.php file.

<?php

namespace App\Controllers;

use App\Models\UserModel;

class UserController extends BaseController {
 
  private $usermodel;
 
  public function __construct() {
	$this->usermodel = new UserModel();
  }
 
  public function index() {
	$data['users'] = $this->usermodel->get_user_list();
	return view('users', $data);
  }
 
  public function create() {
	helper(['form', 'url']);

	if($this->request->getPost('submit')) {
	   $validation =  \Config\Services::validation();
	  
	   $validation->setRules([
		  'name' => ['label' => 'Full Name', 'rules' => 'trim|required'],
		  'email' => ['label' => 'Email Address', 'rules' => 'trim|required|valid_email']
	   ]);
	  
	   if (!$validation->withRequest($this->request)->run()) {
		  echo view('user_create', ['errors' => $validation->getErrors()]);
	   } else {
		  $result = $this->usermodel->create_user($this->request->getPost('name'), $this->request->getPost('email'));
		 
		  if($result === true) {
				return redirect()->to(site_url());
		  } else {
				echo view('user_create', ['error' => 'Error occurred during saving data']);
		  }                                                       
	   }
	} else {
		echo view('user_create');
	}
  }
 
  function update($_id) {
	 helper(['form', 'url']);

	 if($this->request->getPost('submit')) {
	   $validation =  \Config\Services::validation();
	  
	   $validation->setRules([
		  'name' => ['label' => 'Full Name', 'rules' => 'trim|required'],
		  'email' => ['label' => 'Email Address', 'rules' => 'trim|required|valid_email']
	   ]);
	  
	   if (!$validation->withRequest($this->request)->run()) {
		  echo view('user_update', ['errors' => $validation->getErrors()]);
	   } else {
		  $result = $this->usermodel->update_user($_id, $this->request->getPost('name'), $this->request->getPost('email'));
		 
		  if($result === true) {
				return redirect()->to(site_url());
		  } else {
				echo view('user_update', ['error' => 'Error occurred during updating data']);
		  }                                                       
	   }
	 } else {
	   $data['user'] = $this->usermodel->get_user($_id);
	   echo view('user_update', $data);
	 }
  }
 
  function delete($_id) {
	if ($_id) {
		$this->usermodel->delete_user($_id);
	}
	return redirect()->to(site_url());
  }
 
}

Views

The view files are required to display data from server side to user interface (UI). The view files are created under app/Views folder.

List Records

The following PHP file users.php is used to display a list of user records on UI.

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>Codeigniter 4 MongoDB CRUD Example</title>
		<meta name="description" content="The small framework with powerful features">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<link rel="shortcut icon" type="image/png" href="/favicon.ico"/>
		<link rel="stylesheet" type="text/css" href="css/style.css"/>
	</head>
<body>
	<div>
		<h1>Codeigniter 4 MongoDB Create Read Update Delete Example</h1>

		<div>
			<?php echo anchor('/usercontroller/create', 'Create User');?>
		</div>

		<div id="body">
			<?php
			if ($users) {
			?>
			<table class="datatable">
				<thead>
					<tr>
					  <th>Name</th>
					  <th>Email</th>
					  <th>Acions</th>
					</tr>
				</thead>
				<tbody>
					<?php
					  $i = 0;
					  foreach ($users as $user) {
						 $col_class = ($i % 2 == 0 ? 'odd_col' : 'even_col');
						 $i++;
					  ?>
					  <tr class="<?php echo $col_class; ?>">
						 <td>
						   <?php echo $user->name; ?>
						 </td>
						 <td>
						   <?php echo $user->email; ?>
						 </td>
						 <td>
						   <?php echo anchor('/usercontroller/update/' . $user->_id, 'Update'); ?>
							
						   <?php echo anchor('/usercontroller/delete/' . $user->_id, 'Delete', array('onclick' => "return confirm('Do you want delete this record')")); ?>
						 </td>
					  </tr>
					  <?php
					}
					?>
				</tbody>
			</table>
			<?php
			} else {
				echo '<div style="color:red;"><p>No Record Found!</p></div>';
			}
			?>
		</div>
	</div>
</body>
</html>
Table Style

A basic style is applied to the tabular data which are displayed on the UI. The following content is written into public/css/style.css file.

The alternate row (odd or even) color will be different.

table.datatable {
  width:100%;
  border: none;
  background:#fff;
}
table.datatable td.table_foot {
  border: none;
  background: #fff;
  text-align: center;
}
table.datatable tr.odd_col {
  background: none;
}
table.datatable tr.even_col {
  background: #ddd;
}
table.datatable td {
  font-size:10pt;
  padding:5px 10px;
  border-bottom:1px solid #ddd;
  text-align: left;
}
table.datatable th {
  text-align: left;
  font-size: 8pt;
  padding: 10px 10px 7px;  
  text-transform: uppercase;
  color: #fff;
  background:url('../img/table/head.gif') left -5px repeat-x;
  font-family: sans-serif;
}

Create Record

The following code is written into a file user_create.php. This file displays the input fields on the UI where user enters details and saves them into MongoDB.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Codeigniter MongoDB Create Read Update Delete Example</title>
    </head>
    <body>
        <div id="container">
            <h1>Codeigniter 4 MongoDB Create Read Update Delete Example</h1>
                                          
		   <div>
			  <?php echo anchor('/usercontroller', 'Back to Users');?>
		   </div>
                                          
            <div id="body">
				<?php
					if(isset($errors)):
				?>
					<ul style="list-style: none; color: red;">
					<?php foreach ($errors as $err) : ?>
						<li><?= esc($err) ?></li>
					<?php endforeach ?>
					</ul>
				<?php
					endif;
				?>
				
                <?php
					if (isset($error)) {
					  echo '<p style="color:red;">' . $error . '</p>';
					}
                ?>
 
                <?php
					$attributes = array('name' => 'form', 'id' => 'form');
					echo form_open(uri_string(), $attributes);
                ?>
 
                <h5>Full Name</h5>
                <input type="text" name="name" value="<?php echo set_value('name');?>" size="50" />
 
                <h5>Email Address</h5>
                <input type="text" name="email" value="<?php echo set_value('email');?>" size="50" />
 
                <p><input type="submit" name="submit" value="Submit"/></p>
               
                <?php echo form_close(); ?>
            </div>
        </div>
    </body>
</html>

Update Record

The following code is written into a file user_update.php. This form is used to update the existing user information.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Codeigniter MongoDB Create Read Update Delete Example</title>
    </head>
    <body>
        <div id="container">
            <h1>Codeigniter 4 MongoDB Create Read Update Delete Example</h1>
                                          
		   <div>
			  <?php echo anchor('/usercontroller', 'Back to Users');?>
		   </div>
                                          
            <div id="body">
				<?php
					if(isset($errors)):
				?>
					<ul style="list-style: none; color: red;">
					<?php foreach ($errors as $err) : ?>
						<li><?= esc($err) ?></li>
					<?php endforeach ?>
					</ul>
				<?php
					endif;
				?>
				
                <?php
					if (isset($error)) {
					  echo '<p style="color:red;">' . $error . '</p>';
					}
                ?>
 
                <?php
					$attributes = array('name' => 'form', 'id' => 'form');
					echo form_open(uri_string(), $attributes);
                ?>
 
                <h5>Full Name</h5>
                <input type="text" name="name" value="<?php echo isset($user)?$user->name:set_value('name'); ?>" size="50" />
 
                <h5>Email Address</h5>
                <input type="text" name="email" value="<?php echo isset($user)?$user->email:set_value('email'); ?>" size="50" />
 
                <p><input type="submit" name="submit" value="Submit"/></p>
                
                <?php echo form_close(); ?>
            </div>
        </div>
    </body>
</html>

Route Config

You need to change the default controller in the app/Routes/Route.php file as UserController is the default controller instead of Home.

You need to change as $routes->setDefaultController('UserController'); and $routes->get('/', 'UserController::index');.

Testing CodeIgniter 4 MongoDB CRUD Example

You can access the application via CLI interface by executing the command php spark serve on the project’s root directory from the command line tool.

Now access the application in the browser via URL http://localhost:8080

Initially there will be no record, so you will see the following message – No Record Found!

codeigniter 4 mongodb crud

Create new records using the following form.

codeigniter 4 mongodb crud

After successful record creation, you will be redirected to a page where a list of users is displayed.

codeigniter 4 mongodb crud

I have created another record to show you how alternate rows show different colors.

codeigniter 4 mongodb crud

Update record: I am updating the second record using the following form.

codeigniter 4 mongodb crud

After updating the record, you will be again redirected to the list of users page.

codeigniter 4 mongodb crud

Delete a record: I am deleting the first record where a confirmation for deleting the record is required.

codeigniter 4 mongodb crud

After deleting the first record you will be redirected to the user list page.

codeigniter 4 mongodb crud

Hope you got an idea how to build CRUD application using CodeIgniter 4 and MongoDB NoSQL database.

Source Code

Download

Leave a Reply

Your email address will not be published. Required fields are marked *