The original article was published on my personal website: Wing CI — Using Laravel Eloquent ORM in CodeIgniter 2

See https://github.com/johnlui/CodeIgniter-2-with-Eloquent for sample code for this tutorial

Background introduction

The CodeIgniter and Laravel frameworks can be seen as the dominant PHP frameworks in the past few years and in the past two years, with the highest usage and appearance rates.

CI is a lightweight framework that only provides some basic functions such as routing, MVC separation, view loader, Active Record, etc. But this is precisely the reason for its high usage: it provides fewer and more elaborate things and is suitable for most scenarios. CI documents can be regarded as a model of open source software, very clear, detailed, very friendly to novice, very easy to get started.

Laravel is a heavy full-function framework just emerging in the past two years, which can greatly improve the efficiency of development. However, the document of Laravel 4 is not as clear as 3, and there are very few Chinese materials. Many people encounter great difficulties in learning. For example, the complex routing system makes many people who are used to CI automatic mapping at a loss, and the document has only a few sentences. As a result, a considerable number of people are blocked in the first step of using the framework, and their enthusiasm for learning is also eroded.

I recently wrote a series of tutorials Laravel 4 series of introductory tutorials [the most suitable Chinese Language tutorials], visits and response are good, people in need can see.

The cumbersome routing makes many people miss CI’s automatic mapping, and the heavy Framework infrastructure (a Hello World page needs to load more than 150 files) makes Laravel’s performance unsatisfactory in some scenarios. Many people find that Eloquent ORM in Laravel is the strongest place compared with CI after a period of time, so they want to transplant Eloquent to CI. As I have thought before, there is no way to start. Now that we finally know what’s going on, let’s start officially.

Basic preparation

PHP version requirement >= 5.4, which is Eloquent’s minimum requirement.

Download CodeIgniter 2.2.0 at http://www.codeigniter.com/download. After downloading, decompress it somewhere, configure HTTP service software and run the website. If you have seen the following pictures, you can continue to do the following:
Wing CI --- Using Laravel Eloquent ORM in CodeIgniter 2

Begin grafting

We use Composer to load and manage Eloquent. Composer generates an automatic load(autoload) Documents, we only needrequireThis file allows you to use all packages installed through Composer. Now we will use Composer in the CodeIgniter project to create a new composer. JSON under its root directory:

  "require": {
    "php": ">=5.4.0",
    "illuminate/database": "*"

Then runcomposer updateIn a moment, the Composer system is created and the illuminate / database package is installed.

Then buildapplication/third_party/eloquent.php


defined('BASEPATH') OR exit('No direct script access allowed');

use Illuminate\Database\Capsule\Manager as Capsule;

// Autoload automatic loading
require BASEPATH.'../vendor/autoload.php';

// Load the database configuration file
require_once APPPATH.'config/database.php';

// Eloquent ORM
$capsule = new Capsule;



This file will help us introduce Composer's automatic loading file and initialize Eloquent, which loads a database configuration file and adds it at the end of `application/config/database.php'(note replacing the database name and password):

$db['eloquent'] = [
  'driver'    => 'mysql',
  'host'      => 'localhost',
  'database'  => 'ci',
  'username'  => 'root',
  'password'  => 'password',
  'charset'   => 'utf8',
  'collation' => 'utf8_general_ci',
  'prefix'    => ''

Next, we need to introduce the above file when the CI application starts, and add it at the end of the outermost `index.php':

 * --------------------------------------------------------------------
 * LOAD Laravel Eloquent ORM
 * --------------------------------------------------------------------

require APPPATH.'third_party/eloquent.php';

> Note that this code must be placed before `require_once BASEPATH.'core/CodeIgniter.php'; `this line of ***!

Then, start using Eloquent to modify the `index ()'in `application/controllers/welcome.php` as follows:

public function index()
    $data['article'] = Article::first();
    $this->load->view('home', $data);

New `application/views/home.php':
<!DOCTYPE html>
<html lang="en">
  <meta charset="UTF-8">
  <title>CI2 with Eloquent</title>

    <?php echo $article->title; ?>

<div class="content">
      <?php echo $article->content; ?>


Now let’s fill the database with the data we need to use and run the SQL statement:


CREATE TABLE `articles` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(255) DEFAULT NULL,
  `content` longtext,
  PRIMARY KEY (`id`)

/*!40000 ALTER TABLE `articles` DISABLE KEYS */;

INSERT INTO `articles` (`id`, `title`, `content`)
    (1,'I'm the title', '

<h3> I am the content.~~</h3>

<p> I'm really content, don't believe it, hum O</p>

    (2,'I'm the title','

<h3> I am the content.~~</h3>

<p> I'm really content, don't believe it, hum O</p>


/*!40000 ALTER TABLE `articles` ENABLE KEYS */;

Then build a model and build a new one.application/models/Article.phpDocument:


defined('BASEPATH') OR exit('No direct script access allowed');

* Article Model
class Article extends Illuminate\Database\Eloquent\Model
  public $timestamps = false;

Finally, modifycomposer.jsonAdd the models folder to the autoload:

    "require": {
        "php": ">=5.4.0",
    "illuminate/database": "*"
  "autoload": {
    "classmap": [

Functioncomposer dump-autoloadRefresh the page! You will see the following pictures:

Wing CI --- Using Laravel Eloquent ORM in CodeIgniter 2

Congratulations! Eloquent successfully grafted CodeIgniter 2!

CodeIgniter 3 is in the DEV stage. It supports Composer natively and can directly modify the composer. JSON file. The configuration mode is exactly the same as that of 2.

Resource summary

  1. CodeIgniter 2 with Eloquent, GitHub address: https://github.com/johnlui/CodeIgniter-2-with-Eloquent
  2. Building your own PHP framework step by step with Composer (4) – Using ORM
  3. Eloquent Chinese Document
  4. Download CodeIgniter
  5. illuminate/database