In this tutorial, we will implement the steps to integrate MongoDB with CodeIgniter 4 and perform basic CRUD operations.
Step 1: Set Up CodeIgniter 4
If you haven’t already set up CodeIgniter 4, you can create a new project with Composer:
composer create-project codeigniter4/ci4mongodb
OR
Create ci4mongodb in your XAMPP’s htdocs folder and navigate to the project directory:
Step 2: Install MongoDB PHP Driver
To connect MongoDB with CodeIgniter, you need to install the MongoDB PHP driver. Run the following command using Composer:
composer require mongodb/mongodb
Step 3: Configure MongoDB Connection
Create a library class to manage the MongoDB connection. In CodeIgniter 4, database connections are typically defined in the configuration files, but for MongoDB, we will create a custom connection file.
Create a new file: app/Library/MongoDbConnection.php
namespace App/Libraries;
use MongoDB/Client;
class MongoDbConnection {
protected $client;
protected $db;
public function __construct() {
// Connect to MongoDB
$this->client = new Client("mongodb://localhost:27017");
// Select the database
$this->db = $this->client->selectDatabase('ci4mongo_db');
}
public function getCollection($collection) {
return $this->db->selectCollection($collection);
}
}
This class will manage the connection to MongoDB. It uses the MongoDBClient
class provided by the MongoDB PHP driver.
Note: Please replace the (/) with a backward slash for the following code.
namespace App/Libraries;
use MongoDB/Client;
Step 4: Create a Model to Display a list of records in Server-side DataTables
Now that we have the MongoDB connection, let’s create a model to handle CRUD operations.
Create a file app/Models/login/LoginDeferModel.php
:
namespace App/Models/login;
use App/Libraries/MongoDbConnection;
class LoginDeferModel {
protected $collection;
public function __construct() {
$mongoDB = new MongoDbConnection();
$this->collection = $mongoDB->getCollection('login_info');
}
public function getRows($searchValue, $start, $length) {
$filter = [];
if ($searchValue) {
// $filter = ['name' => ['$regex' => $searchValue, '$options' => 'i']];
$filter = ['$or' => [
['name' => ['$regex' => $searchValue, '$options' => 'i']],
['email' => ['$regex' => $searchValue, '$options' => 'i']],
['mobile_number' => ['$regex' => $searchValue, '$options' => 'i']],
]];
}
$options = [
'skip' => $start,
'limit' => $length,
];
$rows = $this->collection->find($filter, $options)->toArray();
$totalRecords = $this->collection->countDocuments();
$filteredRecords = $this->collection->countDocuments($filter);
return [
'data' => $rows,
'recordsTotal' => $totalRecords,
'recordsFiltered' => $filteredRecords,
];
}
}
Note: Please replace the (/) with a backward slash for the following code.
namespace App/Models/login;
use App/Libraries/MongoDbConnection;
Step 5: Create a Controller for CRUD Operations
Now let’s create a controller to handle the requests.
Create a new file app/Controllers/login/Login.php
:
namespace App/Controllers/login;
use App/Controllers/BaseController;
use App/Models/login/LoginDeferModel;
class Login extends BaseController {
protected $login;
public function __construct() {
$this->loginDefer = new LoginDeferModel();
$this->ip_address = $_SERVER['REMOTE_ADDR'];
$this->datetime = date("Y-m-d H:i:s");
}
public function index() {
$this->list();
}
public function list() {
$data = [];
$data['content_title'] = 'List | CodeIgniter 4 MongoDB';
$data['main_content'] = 'login/list';
echo view("innerpages/template", $data);
}
public function datatable() {
$draw = $this->request->getPost('draw');
$start = $this->request->getPost('start');
$length = $this->request->getPost('length');
$searchValue = $this->request->getPost('search')['value'];
$result = $this->loginDefer->getRows($searchValue, (int) $start, (int) $length);
$arrayList = $this->getRows($start, $result['data']);
$response = [
'draw' => (int) $draw,
'recordsTotal' => $result['recordsTotal'],
'recordsFiltered' => $result['recordsFiltered'],
'data' => $arrayList,
];
echo json_encode($response);
}
function getRows($start, $result) {
$arrayList = [];
foreach ($result as $row) {
$action = '
<a href="'.base_url('edit?id=' . (string) $row->_id).'" class="btn btn-primary">Edit</a>
<button type="button" name="btn-delete" data-id="'.(string) $row->_id.'" class="btn btn-danger">Delete</button>
';
$arrayList [] = [
++$start,
$row->name,
$row->email,
$row->mobile_number,
$action,
];
}
return $arrayList;
}
}
Note: Please replace the (/) with a backward slash for the following code.
namespace App/Controllers/login;
use App/Controllers/BaseController;
use App/Models/login/LoginDeferModel;
Step 6: Define Routes
You need to define routes to access the CRUD operations. Open app/Config/Routes.php
and add the following:
$routes->get('/', 'login/Login::index');
$routes->get('add', 'login/Login::add');
$routes->get('edit', 'login/Login::edit');
$routes->post('create', 'login/Login::create');
$routes->post('update', 'login/Login::update');
$routes->post('delete', 'login/Login::delete');
$routes->post('datatable', 'login/Login::datatable');
Note: Please replace the (/) with a backward slash for the following code.
Step 7: Create views header.php, footer.php, and template.php for reusable structure.
Create a new file app/View/innperpages/header.php
:
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php echo $content_title; ?></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/2.1.7/css/dataTables.dataTables.min.css">
<link href="https://cdn.datatables.net/buttons/3.1.2/css/buttons.dataTables.min.css">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/2.1.7/js/dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/3.1.2/js/dataTables.buttons.min.js"></script>
</head>
<body>
<div class="container-fluid p-5 bg-primary text-white text-center">
<h1><?php echo $content_title; ?></h1>
</div>
<div class="container mt-5">
<div class="row">
<div class="col-sm-3"></div>
<div class="col-sm-6">
<div class="result"></div>
</div>
</div>
</div>
Create a new file app/View/innperpages/footer.php
:
</body>
</html>
Create a new file app/View/innperpages/template.php
:
<?php
echo view('innerpages/header');
echo view($main_content);
echo view('innerpages/footer');
Step 7: Create views to display CRUD Interface
Create a new file app/View/login/list.php
:
<div class="container mt-5">
<div class="row">
<div class="col-sm-2"></div>
<div class="col-sm-8">
<a href="<?php echo base_url('add') ?>" class="btn btn-primary">+ Add User</a>
<div class="table-responsive mt-5">
<table id="table-login" width="100%" class="table table-striped">
<thead>
<tr>
<th>No.</th>
<th>Name</th>
<th>Email</th>
<th>Mobile No.</th>
<th>#</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
<?php
echo view('login/scripts');
?>
Create a new file app/View/login/scripts.php
:
<script type="text/javascript">
$(document).ready(function() {
var table_login = $('#table-login').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url" : "<?= base_url('datatable') ?>",
"type" : "POST",
},
});
});
</script>
In this tutorial, we learned how to integrate MongoDB with CodeIgniter 4 and perform basic CRUD list operations.