LoginSignup
29
27

More than 5 years have passed since last update.

LaravelのQueryBuilderやEloquentを素のPHPで使う

Posted at

Laravelで利用できる便利ツールであるQueryBuilderやEloquentを素のPHPや他のフレームワークで利用する方法。

前提

  • composerはインストールされている
  • Mac El Capitan(じゃなくてもいいですが)

インストール

composerで本体のilluminate/databaseと、依存関係にあるilluminate/eventsをインストールします。

mkdir test
cd test

composer require illuminate/database
composer require illuminate/events

dbconfig.php

基本的には本家サイトの通りにすればいいですが、設定部分は外部ファイルにしてみました。

<?php

    require_once 'vendor/autoload.php';

    use Illuminate\Database\Capsule\Manager as Capsule;

    $capsule = new Capsule;

    $capsule->addConnection([
        'driver'    => 'mysql',
        'host'      => 'localhost',
        'database'  => 'testdb',
        'username'  => 'root',
        'password'  => 'root',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ]);

    // 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();

test.php

dbconfig.phpを読み込んで処理を書きます。

QueryBuilderは何もしなくても利用できます。

EloquentはModel Classを定義することで使えます。既存のテーブルを利用する場合は、public $timestamps = false;とします。

もちろんshopsというテーブルがあることが前提です。

<?php

    require 'dbconfig.php';

    //--- QueryBuilder ------------

    $shops = $capsule::table('shops')->get();

    print_r($shops);

    //--- Eloquent ----------------

    class Shop extends Illuminate\Database\Eloquent\Model
    {
        public $timestamps = false;
    }

    //select
    $shops = Shop::all();

    print_r($shops);

    //insert
    $shop = new Shop();

    $shop->name = "Poo";

    $shop->save();

ほとんどLaravelと同じです。

その他

あとは、Laravelのリファレンスを見ればいいでしょう。

29
27
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
27