Using Laravel's Eloquent ORM Independently
Introduction to Standalone Eloquent ORM
The Eloquent ORM from Laravel can be utilized independently of the full framework. This powerful database toolkit offers several advantages for PHP developers seeking a robust database abstraction layer without the entire Laravel ecosystem.
Benefits of Using Standalone Eloquent
- Expressive and intuitive syntax for database operations
- Powerful query builder with fluent interface
- ActiveRecord-style ORM for object-relational mapping
- Schema builder for database migrations
- Strong performance characteristics
- High code reusability across projects
System Requirements
The standalone version is compatible with PHP 7.2+ and supports the following database systems:
- MySQL 5.6+
- PostgreSQL 9.4+
- SQLite 3.8.8+
- SQL Server 2017+
Installation
Begin by installing the package via Composer:
composer require illuminate/database
For projects requiring Eloquent observers, you'll also need:
composer require "illuminate/events"
Configuration and Setup
The first step is to create a Capsule manager instance. Capsule provides a convenient way to configure the database components outside of Laravel:
<?php
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Events\Dispatcher;
use Illuminate\Container\Container;
$capsule = new Capsule;
$capsule->addConnection([
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'your_database',
'username' => 'your_username',
'password' => 'your_password',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
]);
// Optional: Set the event dispatcher for Eloquent models
$capsule->setEventDispatcher(new Dispatcher(new Container));
// Optional: Make Capsule available globally via static methods
$capsule->setAsGlobal();
// Optional: Boot the Eloquent ORM
$capsule->bootEloquent();
?>
Using the Query Builder
Once configured, you can use the query builder to interact with your database:
// Retrieve users with more than 100 votes
$activeUsers = Capsule::table('users')
->where('votes', '>', 100)
->get();
// Execute raw SQL with parameter binding
$results = Capsule::select('SELECT * FROM users WHERE id = ?', [1]);
Using the Schema Builder
The schema builder allows you to modify your dtaabase structure:
// Create a new table
Capsule::schema()->create('users', function ($table) {
$table->increments('id');
$table->string('email')->unique();
$table->timestamps();
});
// Modify an existing table
Capsule::schema()->table('users', function ($table) {
$table->string('first_name');
$table->string('last_name');
});
Using Eloquent Models
Define your models to work with Eloquent ORM:
<?php
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
// Specify the table if not following naming conventions
protected $table = 'users';
// Define which fields are mass assignable
protected $fillable = ['name', 'email', 'password'];
// Define any relationships with other models
public function posts()
{
return $this->hasMany('Post');
}
}
?>
Once your models are defined, you can interact with your database:
// Retrieve all users
$allUsers = User::all();
// Find a user by ID
$user = User::find(1);
// Query users with conditions
$activeUsers = User::where('active', 1)->get();
// Create a new user
$newUser = User::create([
'name' => 'John Doe',
'email' => 'john@example.com',
'password' => bcrypt('password')
]);
// Update a user
$user = User::find(1);
$user->name = 'Jane Doe';
$user->save();
Practical Implementation Example
Here's a complete example of how to implement the standalone Eloquent ORM in a project:
<?php
// Include Composer autoloader
require __DIR__ . '/vendor/autoload.php';
// Define your Eloquent model
class User extends Illuminate\Database\Eloquent\Model {}
// Database configuration
$dbConfig = [
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'your_database',
'username' => 'your_username',
'password' => 'your_password',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
];
// Initialize Capsule
$capsule = new Illuminate\Database\Capsule\Manager as Capsule;
$capsule->addConnection($dbConfig);
$capsule->setAsGlobal();
$capsule->bootEloquent();
// Example usage
$users = User::orderBy('created_at', 'desc')->limit(10)->get();
foreach ($users as $user) {
echo $user->name . ': ' . $user->email . PHP_EOL;
}
?>
Remember to implement proper autoloading for your models in a production environment to ensure all classes are properly loaded.