Integrate Laravel Eloquent in Code Igniter

Eloquent in Code Igniter

Code Igniter popular know as CI is one of the simple yet powerful PHP framework. Founded in the year 2006, it is fast, reliable, extremely light weight and works on Model-View-Controller pattern. It offers clear and thorough documentation which helps programmers to get started easily. 


But when we compare code igniter’s active records with laravel’s eloquent, laravel beats ci hands down. Now Imagine, how cool it could be if we were able to integrate eloquent in code igniter. Lets see how to do this.

Integrate Laravel Eloquent in Code Igniter

  1. Require Illuminate/Database package
  2. Configure Hooks
  3. Testing Laravel Eloquent

 

1. Require Illuminate/Database package

I’m assuming you already have composer installed in your system. Open your terminal, navigate to the code igniter folder and run the following command

composer require illuminate/database 5.1.16

Above command will pull the illuminate database package from packagist and place it under your vendor directory. Then we need to autoload model files. So, open your composer.json file and add the following code

"autoload": {
    "classmap": [
       "application/models"
    ]
}

After adding the above code, your composer.json file looks like the following

{
   "require": {
      "illuminate/database": "5.1.16"
   },
   "autoload": {
        "classmap": [
           "application/models"
         ]
    }
}

Finally add the following line to the top of index.php file on the root directory

require_once 'vendor/autoload.php';

run composer dump-autoload to autoload model files.

 

2. Configure Hooks

Firstly, we need to tell code igniter that we are going to use hooks. Open up application/config/config.php and enable hooks.

$config['enable_hooks'] = TRUE;

then open application/config/hooks.php and add the following code

$hook['post_controller_constructor'][] = [
    'class'    => 'EloquentHook',
    'function' => 'bootEloquent',
    'filename' => 'EloquentHook.php',
    'filepath' => 'hooks'
];

This hook is called after controller’s constructor method is executed. Lets create EloquentHook.php inside application/hooks folder and add the following code.

<?php

use Illuminate\Database\Capsule\Manager as Capsule;

class EloquentHook {

	/**
	 * Holds the instance
	 * @var object
	 */
	protected $instance;

	/**
	 * Gets CI instance
	 */
	private function setInstance() {
		$this->instance =& get_instance();
	}

	/**
	 * Loads database
	 */
	private function loadDatabase() {
		$this->instance->load->database(); 
	}

	/**
	 * Returns the instance of the db
	 * @return object
	 */
	private function getDB() {
		return $this->instance->db;
	}

	public function bootEloquent() {

		$this->setInstance();

		$this->loadDatabase();

		$config = $this->getDB();

		$capsule = new Capsule;

		$capsule->addConnection([
			'driver'    => 'mysql',
		    'host'      => $config->hostname,
		    'database'  => $config->database,
		    'username'  => $config->username,
		   	'password'  => $config->password,
		   	'charset'   => $config->char_set,
		   	'collation' => $config->dbcollat,
		   	'prefix'    => $config->dbprefix,
		]);

		$capsule->setAsGlobal();
		$capsule->bootEloquent();
	}

}

 

Here $config variable holds the database config variable values that you have specified in application/config/database.php.

 

3. Testing Laravel Eloquent

Now that we are done with configuring, lets test eloquent. Your model will use \Illuminate\Database\Eloquent\Model

Example User.php

<?php 

use \Illuminate\Database\Eloquent\Model as Eloquent;

class User extends Eloquent {

    protected $table = "users"; // table name
}

NOTE : Don’t forget to run composer dump-autoload every time you create new model file. If not, you will see class not found exception when you try to access your model file.

Now in your default controller query the user model

User::all(); // will fetch all users

User::find(1); // will fetch user with id 1

User::where('id', '>', 1)->get(); // will fetch users with id > 1

Thats it! Thats all you need to integrate eloquent in code igniter framework. Laravel’s eloquent works perfect in all code igniter versions from 2.2 and above.

 

Happy Coding!


I'm a full stack freelance PHP developer. I have worked on various PHP frameworks like Laravel, Code Igniter, Magento, Wordpress.