Jens Segers on

Using Eloquent without Laravel

Not many people know this, but you can actually use the Laravel database component outside the Laravel framework (PyroCMS is actually using it in their CMS). This means you can use Eloquent in whatever project you want! The database component contains a Capsule manager class, which was originally created by Dan Horrigan, that takes care of creating a Laravel container and loading the required classes.

To use the database component, include it in your project with the following command, or by editing your composer.json file, and run composer install.

composer require illuminate/database

Then it's basically following the readme on how to use the Capsule manager.

require 'vendor/autoload.php';    

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'    => '',
]);

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

// Setup the Eloquent ORM
$capsule->bootEloquent();

That's it, now you can start using all of the awesome Eloquent and query builder stuff. For the query builder you can use the static Capsule methods:

$users = Capsule::table('users')->where('votes', '>', 100)->get();

And for Eloquent, just extend the Eloquent model like this:

class User extends Illuminate\Database\Eloquent\Model {}
    
$users = User::where('votes', '>', 1)->get();

For more information about the query builder and Eloquent, check out http://laravel.com/docs/eloquent

Webmentions

Tweet about this blog post and you will appear below!