How to use Eloquent ORM outside Laravel

Installing Eloquent Capsule

In order to use Eloquent, you just need to install it via Composer into your project using following command.

$ composer require "illuminate/database"

Now, once installed, to actually use Eloquent, you need to first create a new Capsule manager instance. Capsule aims to make configuring the library for usage outside of the Laravel framework as easy as possible. Here’s how you can create database configuration.

use Illuminate\Database\Capsule\Manager as Capsule;

$capsule = new Capsule;

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

Executing queries

Once the Capsule instance has been registered, you can use it like this.

$users = Capsule::table('users')->where('votes', '>', 100)->get();
$results = Capsule::select('select * from users where id = ?', [1]);
Capsule::schema()->create('users', function ($table) {
    $table->increments('id');
    $table->string('email')->unique();
    $table->timestamps();
});
class User extends Illuminate\Database\Eloquent\Model {
    // code goes here
}

$users = User::where('votes', '>', 1)->get();

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *