CodeIgniter 4 MongoDB Tutorial
    About Lesson

    In this tutorial, we will implement the steps to integrate MongoDB with CodeIgniter 4 and perform basic Login 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 Login Operations

    Now that we have the MongoDB connection, let’s create a model to handle Login 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 Login 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->session = ConfigServices::session();

    $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 login() {
    if($this->session->get('login_id')) {
    return redirect()->to(base_url('myprofile'));
    }
    $data = [];
    $data['content_title'] = 'Login | CodeIgniter 4 MongoDB';
    $data['main_content'] = 'login/login';
    echo view("innerpages/template", $data);
    }

    public function myprofile() {
    if($this->session->get('login_id')) {
    $where = [
    '_id' => new MongoDBBSONObjectId($this->session->get('login_id')),
    ];
    $result = $this->login->getEntry($where);
    if($result) {
    $data = [];
    $data['content_title'] = 'My Profile | CodeIgniter 4 MongoDB | ' . $this->session->get('login_name');
    $data['main_content'] = 'login/myprofile';
    $data['result'] = $result;
    echo view("innerpages/template", $data);
    } else {
    return redirect()->to(base_url('login'));
    }
    } else {
    return redirect()->to(base_url('login'));
    }
    }

    public function logout() {
    $this->session->destroy();
    return redirect()->to(base_url('login'));
    }

    public function authenticate() {
    $email = $this->request->getPost('email');
    $password = $this->request->getPost('password');
    $where = [
    'email' => $email,
    'password' => md5($password),
    'status' => '1',
    ];
    $result = $this->login->getEntry($where);
    if($result) {
    $data = [
    'login_id' => (string) $result->_id,
    'login_email' => $result->email,
    'login_name' => $result->name,
    'login_mobile_number' => $result->mobile_number,
    'user_status' => $result->status,
    'login_status' => TRUE,
    ];
    $this->session->set($data);
    $json = [
    'message' => "<span class='text-success'>Logged in successfully.</span>",
    'location' => base_url('myprofile'),
    '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');

    // Login
    $routes->get('login', 'login/Login::login');
    $routes->post('authenticate', 'login/Login::authenticate');

    // My Profile
    $routes->get('myprofile', 'login/Login::myprofile');
    $routes->get('logout', 'login/Login::logout');

     

    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 for login

    Create a new file app/View/login/login.php:

    Login CodeIgniter 4 MongoDB

     

    <div class="container mt-5">
    <div class="row">
    <div class="col-sm-3"></div>

    <div class="col-sm-6">
    <a href="<?php echo base_url() ?>" class="btn btn-danger">Back</a>
    <form method="post" id="form-login" autocomplete="off" class="mt-3">
    <div class="form-group mt-3">
    <label>Email</label>
    <input type="email" name="email" placeholder="Email" class="form-control" required>
    </div>
    <div class="form-group mt-3">
    <label>Password</label>
    <input type="password" name="password" placeholder="Password" class="form-control" required>
    </div>
    <div class="form-group mt-3">
    <button type="submit" class="btn btn-primary">Login</button>
    </div>
    </form>
    </div>
    </div>
    </div>

    <?php
    echo view('login/scripts');
    ?>

     

    Create a new file app/View/login/myprofile.php:

    My Profile CodeIgniter 4 MongoDB Junaid Shaikh

    <div class="container mt-5">
    <div class="row">
    <div class="col-sm-3"></div>

    <div class="col-sm-6">
    <a href="<?php echo base_url() ?>" class="btn btn-danger">Back</a>

    <form method="post" id="form-update-login" autocomplete="off" class="mt-3">
    <input type="hidden" name="id" value="<?php echo (string) $result->_id; ?>">
    <div class="form-group">
    <label>Name</label>
    <input type="text" name="name" placeholder="Name" class="form-control" value="<?php echo $result->name; ?>" required>
    </div>
    <div class="form-group mt-3">
    <label>Email</label>
    <input type="email" name="email" placeholder="Email" class="form-control" value="<?php echo $result->email; ?>" required>
    </div>
    <div class="form-group mt-3">
    <label>Mobile No.</label>
    <input type="text" name="mobile_number" placeholder="Mobile No." class="form-control" maxlength="10" minlength="10" value="<?php echo $result->mobile_number; ?>" required>
    </div>
    <div class="form-group mt-3">
    <label>Password</label>
    <input type="password" name="password" placeholder="Password" class="form-control">
    </div>
    <div class="form-group mt-3">
    <button type="submit" class="btn btn-primary">Update</button>
    </div>
    </form>

    </div>
    </div>
    </div>

    <?php
    echo view('login/scripts');
    >

     

    Create a new file app/View/login/scripts.php:

    <script type="text/javascript">
    $(document).ready(function() {
    $("body").on("submit", "#form-login", function(e) {
    e.preventDefault();
    let data = $(this).serialize();
    $.post('<?php echo base_url("authenticate") ?>', data, function(result) {
    if(result.status) {
    $(".result").html(result.message);
    let link_open = window.open(result.location, "_self");
    link_open.focus();
    } else {
    $(".result").html(result.message);
    }
    }, 'json');
    });

    $("body").on("submit", "#form-update-login", function(e) {
    e.preventDefault();
    let data = $(this).serialize();
    $.post('<?php echo base_url("update") ?>', data, function(result) {
    if(result.status) {
    $(".result").html(result.message);
    let link_open = window.open(result.location, "_self");
    link_open.focus();
    } else {
    $(".result").html(result.message);
    }
    }, 'json');
    });
    });
    </script>

     


     

    In this tutorial, we learned how to integrate MongoDB with CodeIgniter 4 and perform basic Login operations.

    Get the source code for free: Click Here