Complete CodeIgniter 4 Model Events Tutorial

Reading Time: 8 minutes
9,331 Views

Inside this Tutorial we will discuss the Model events of CodeIgniter 4. Model events are also termed as Life cycle of a Model. There are 8 callbacks available by the help of which we can fire event and track model status.

We will see the complete codeigniter 4 model events step by step. It will be very interesting to see and learn.

$beforeInsert, $afterInsert, $beforeUpdate, $afterUpdate, $beforeFind, $afterFind, $beforeDelete, $afterDelete

Learn More –

Let’s get started.


CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Environment (.env) Setup

When we install CodeIgniter 4, we will have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Either we can do via renaming file as simple as that. Also we can do by terminal command.

Open project in terminal

cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 
 
CI_ENVIRONMENT = development

Now application is in development mode.


What are Model Events in CodeIgniter 4?

Events which fires when model perform any activity is called Model events.

Model normally do CRUD operation which means Create Read Update & Delete. For all these operation, model have events for all.

For Create Operation , Pair Events as $beforeInsert, $afterInsert.

For Read Operation , Pair Events as $beforeFind, $afterFind.

For Update Operation , Pair Events as $beforeUpdate, $afterUpdate.

For Update Operation , Pair Events as $beforeDelete, $afterDelete.

These are also called as Lifecycle of a Model or Callbacks of Model in CodeIgniter 4. We can find all model events or callbacks into Model file.

// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert = [];
protected $afterInsert = [];
protected $beforeUpdate = [];
protected $afterUpdate = [];
protected $beforeFind = [];
protected $afterFind = [];
protected $beforeDelete = [];
protected $afterDelete = [];

Create Model & Events Callbacks Settings

Open project into terminal and run this command.

$ php spark make:model Student --suffix

It will creates a file i.e StudentModel.php into /app/Models folder. Open file –

<?php

namespace App\Models;

use CodeIgniter\Model;

class StudentModel extends Model
{
    protected $DBGroup = 'default';
    protected $table = 'students'; // Assume we have a students table
    protected $primaryKey = 'id';
    protected $useAutoIncrement = true;
    protected $insertID = 0;
    protected $returnType = 'array';
    protected $useSoftDelete = false;
    protected $protectFields = true;
    protected $allowedFields = [
        "name",
        "email",
        "mobile",
    ];

    // Dates
    protected $useTimestamps = false;
    protected $dateFormat = 'datetime';
    protected $createdField = 'created_at';
    protected $updatedField = 'updated_at';
    protected $deletedField = 'deleted_at';

    // Validation
    protected $validationRules = [];
    protected $validationMessages = [];
    protected $skipValidation = false;
    protected $cleanValidationRules = true;

    // Callbacks
    protected $allowCallbacks = true;
    protected $beforeInsert = ["callBeforeInsert"];
    protected $afterInsert = ["callAfterInsert"];
    protected $beforeUpdate = ["callBeforeUpdate"];
    protected $afterUpdate = ["callAfterUpdate"];
    protected $beforeFind = ["callBeforeFind"];
    protected $afterFind = ["callAfterFind"];
    protected $beforeDelete = ["callBeforeDelete"];
    protected $afterDelete = ["callAfterDelete"];

    protected function callBeforeInsert(array $data)
    {
        log_message("info", "Running method before insert");

        return $data;
    }

    protected function callAfterInsert(array $data)
    {
        // $data -> It contains a model object with values

		//log_message("info", "After create running " . json_encode($data));
        
        //log_message("info", "Running method after insert " . $data["data"]["email"]);
      
        log_message("info", "Running method after insert");

        return $data;
    }

    protected function callBeforeUpdate(array $data)
    {
        //log_message("info", "Running method before update ". json_encode($data));
      
        log_message("info", "Running method before update");

        return $data;
    }

    protected function callAfterUpdate(array $data)
    {
        //log_message("info", "Running method after update ". json_encode($data));
      
        log_message("info", "Running method after update");

        return $data;
    }

    protected function callBeforeFind(array $data)
    {
        //log_message("info", "Running method before find ". json_encode($data));
      
        log_message("info", "Running method before find");

        return $data;
    }

    protected function callAfterFind(array $data)
    {
        //log_message("info", "Running method after find". json_encode($data));
      
        log_message("info", "Running method after find");

        return $data;
    }

    protected function callBeforeDelete(array $data)
    {
        //log_message("info", "Running method before delete ". json_encode($data));
      
        log_message("info", "Running method before delete");

        return $data;
    }

    protected function callAfterDelete(array $data)
    {
        //log_message("info", "Running method after delete". json_encode($data));
      
        log_message("info", "Running method after delete");

        return $data;
    }
}

Here, inside this model we have created methods and attached with each event of StudentModel. Methods are also know as callbacks.

protected $beforeInsert = ["callBeforeInsert"];

Above line means before insert any data from Model, callback method callBeforeInsert will be called.

log_message() This method is to create logs into application. For more information about logger and it’s settings, click here for CodeIgniter 4 Logs Tutorial


Routes Settings

Open Routes.php from /app/Config folder.

//...

$routes->get("list-data", "StudentController::index");
$routes->get("add-data", "StudentController::addStudent");
$routes->get("update-data", "StudentController::editStudent");
$routes->get("delete-data", "StudentController::deleteStudent");

//...

Controller Settings

Open project in terminal and run this command to create controller.

$ php spark make:controller Student --suffix

It will creates a file i.e StudentController.php into /app/Controllers folder.

<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\StudentModel;

class StudentController extends BaseController
{
	public function index()
	{
		// find student data
		$student_obj = new StudentModel();

		$data = $student_obj->find(3); // Let's assume 3 is ID of a student
	}

	public function addStudent()
	{
		$data = [
			"name" => "Sample name",
			"email" => "sample_name@gmail.com",
			"mobile" => "9875453132"
		];

		// object of StudentModel
		$student_obj = new StudentModel();

		$student_obj->insert($data); // We are inserting data into table
	}

	public function editStudent()
	{
		$data = [
			"name" => "Sample name update",
			"email" => "sample_name_update@gmail.com",
			"mobile" => "9875453132"
		];

		// object of StudentModel
		$student_obj = new StudentModel();

		$student_obj->update(5, $data); // Assuming ID = 5 will be updated.
	}

	public function deleteStudent()
	{
		// delete operation of student
		$student_obj = new StudentModel();

		$student_obj->delete(6); // Assuming ID = 6 will be deleted.
	}
}

Application Testing

Open project terminal and start development server via command:

php spark serve

URL to Find data: http://localhost:8080/list-data

When this runs, calls a pair of Model events i.e $beforeFind & $afterFind. The callbacks simply logs into a log file.

Logs file by default we can find at /writable/logs folder.

INFO - 2021-02-19 12:21:57 --> Running method before find
INFO - 2021-02-19 12:21:57 --> Running method after find

Here is the callbacks logs messages saved.

URL to Find data: http://localhost:8080/add-data

When this runs, calls a pair of Model events i.e $beforeInsert & $afterInsert. The callbacks simply logs into a log file.

INFO - 2021-02-19 12:21:57 --> Running method before insert
INFO - 2021-02-19 12:21:57 --> Running method after insert

… so on for all operations.

We hope this article helped you to learn about Complete CodeIgniter 4 Model Events Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.