Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

Codeigniter3でLaravelのEloquentを使いたい

More than 1 year has passed since last update.

社内のプロジェックトではLaravelとCodeigniterを使っていて
CodeigniterでもLaravelのEloquentを使いたいと思って導入したのでメモ代わりに残しておく。

illuminate/databaseをcomposerでインストール

composer require illuminate/database

 

index.phpでvendor/autoload.phpを読み込む

index.php
/*
 * --------------------------------------------------------------------
 * LOAD THE COMPOSER AUTOLOADFILE
 * --------------------------------------------------------------------
 */
require_once '../vendor/autoload.php';

/*
 * --------------------------------------------------------------------
 * LOAD THE BOOTSTRAP FILE
 * --------------------------------------------------------------------
 *
 * And away we go...
 */
require_once BASEPATH.'core/CodeIgniter.php';

configのautoloadではEloquent modelを継承したクラスは対象外となるので
requireでautoload.phpを読み込む。
(ファイル最下部のCodeIgniter.phpの読み込みの上あたりに追記)

database.phpにDBコネクション周りを追記する

https://github.com/illuminate/database
(githubのREADME通りに記述した)

database.php
use Illuminate\Database\Capsule\Manager as Capsule;

$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'username',
    'password' => 'password',
    'database' => 'database',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

$capsule = new Capsule;

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

// Set the event dispatcher used by Eloquent models... (optional)
use Illuminate\Events\Dispatcher;
use Illuminate\Container\Container;
$capsule->setEventDispatcher(new Dispatcher(new Container));


// Make this Capsule instance available globally via static methods... (optional)
$capsule->setAsGlobal();

// Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher())
$capsule->bootEloquent();

Illuminate\Database\Eloquent\Modelを継承したModelを作成する

User.php
<?php
use Illuminate\Database\Eloquent\Model as Eloquent;

class User extends Eloquent
{
    # テーブル名を指定する
    protected $table = 'users';
    # 主キーのデフォルトのカラム名が「id」で設定されているのでカラム名が違う場合はprimaryKeyを指定する
    protected $primaryKey = 'user_id';
}

ControllerでModelを呼び出してみる

User_data.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User_data extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        # modelの読み込み
        $this->load->model('user');
    }

    public function index()
    {
        $user['rows'] = User::all()->toArray();

        $this->load->view('user_data/index', $user)
    }

Eloquentで使える関数は使用可能なので公式ドキュメントを参照すること。
https://readouble.com/laravel/5.5/ja/eloquent.html

参考にさせてもらったサイト
CodeigniterでLaravelのEloquentを使う

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away