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 for CRUD Operations
Now that we have the MongoDB connection, let’s create a model to handle CRUD operations.
Create a file app/Models/login/LoginModel.php
:
namespace App/Models/login;
use App/Libraries/MongoDbConnection;
class LoginModel {
protected $collection;
public function __construct() {
$mongoDB = new MongoDbConnection();
$this->collection = $mongoDB->getCollection('login_info');
}
// Create a new user
public function createEntry($data) {
$result = $this->collection->insertOne($data);
return $result->getInsertedId();
}
// Get all users
public function getEntryList($filter = [], $options = []) {
return $this->collection->find($filter, $options)->toArray();
}
// Get a user by ID
public function getEntry($filter = [], $options = []) {
// return $this->collection->findOne(['_id' => new MongoDBBSONObjectId($id)]);
return $this->collection->findOne($filter, $options);
}
// Update a user by ID
public function updateEntry($filter, $newData) {
// return $this->collection->updateOne(
// ['_id' => new MongoDBBSONObjectId($id)],
// ['$set' => $data]
// );
return $this->collection->updateOne($filter, ['$set' => $newData]);
}
// Delete a user by ID
public function deleteEntry($filter) {
// return $this->collection->deleteOne(['_id' => new MongoDBBSONObjectId($id)]);
return $this->collection->deleteOne($filter);
}
}
This model allows you to perform basic CRUD operations: Create, Read, Update, and Delete. It connects to MongoDB through the MongoDbConnection
class and performs operations on the specified collection.
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/LoginModel;
class Login extends BaseController {
protected $login;
public function __construct() {
$this->login = new LoginModel();
$this->loginDefer = new LoginDeferModel();
$this->ip_address = $_SERVER['REMOTE_ADDR'];
$this->datetime = date("Y-m-d H:i:s");
}
public function delete() {
$id = $this->request->getPost('id');
$where = [
'_id' => new MongoDBBSONObjectId($id),
];
$result = $this->login->deleteEntry($where);
if($result) {
$json = [
'message' => "<span class='text-success'>Selected login has been deleted successfully.</span>",
'status' => true,
];
} else {
$json = [
'message' => "<span class='text-danger'>Something went wrong. Please try again.</span>",
'status' => false,
];
}
echo json_encode($json);
}
}
Note: Please replace the (/) with a backward slash for the following code.
namespace App/Controllers/login;
use App/Controllers/BaseController;
use App/Models/login/LoginModel;
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 delete the record from MongoDB
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",
},
});
$("#table-login tbody").on('click', 'button', function() {
var id = $(this).attr('data-id');
if(this.name == "btn-delete") {
var is_delete = confirm("Are your sure?");
if(is_delete) {
$.post('<?php echo base_url("delete") ?>', {id: id}, function(result) {
if(result.status) {
$(".result").html(result.message);
table_login.ajax.reload();
} else {
$(".result").html(result.message);
}
}, 'json');
}
}
});
});
</script>
In this tutorial, we learned how to integrate MongoDB with CodeIgniter 4 and perform basic CRUD delete operations.