How to utilize Capsule to use Eloquent ORM outside Laravel

Amit Merchant · September 11, 2019 ·

If you love the Laravel as a framework or more specifically its Eloquent ORM like I do then there’s a great chance that you’d like to use this great ORM in your non-Laravel PHP apps as well. And the good news is it’s rather easier than you might think. Laravel provides a standalone pacakge called Capsule which you can use in your own project. It’s a full database toolkit for PHP, providing an expressive query builder, ActiveRecord style ORM, and schema builder. It currently supports MySQL, Postgres, SQL Server, and SQLite.

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 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;

    'driver'    => 'mysql',
    'host'      => 'localhost',
    'database'  => 'database',
    'username'  => 'root',
    'password'  => 'password',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',

2020 is more than a year. Learning 20 minutes a day for 20 days pays off. Udemy online courses start at $9.99.

This is an affiliate link. Making a purchase from it helps run this blog.

Executing queries

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

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

Other core methods may be accessed directly from the Capsule in the same manner as from the DB facade:

$results = Capsule::select('select * from users where id = ?', [1]);

Using The Schema Builder

Capsule::schema()->create('users', function ($table) {

You can even use Eloquent directly using Illuminate\Database\Eloquent\Model by creating table models.

class User extends Illuminate\Database\Eloquent\Model {
    // code goes here

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

Hi there! I'm Amit. I write articles about all things web development. If you like what I write, buy me a coffee. I'd highly appreciate that. Cheers!


Follow me on Twitter @amit_merchant