Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

How to utilize Capsule to use Eloquent ORM outside Laravel

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"

Usage

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

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

You can also create table schemas just like you’d be used to within Laravel.

Capsule::schema()->create('users', function ($table) {
    $table->increments('id');
    $table->string('email')->unique();
    $table->timestamps();
});

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();
Learn the fundamentals of PHP 8 (including 8.1, 8.2, 8.3, and 8.4), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?