⬡ Lacelium
⌘K
Version 2.x ▾

Eloquent ORM Overview

Introduction

The Eloquent ORM included with Lacelium provides a beautiful, simple ActiveRecord implementation for working with your database. When using Eloquent, each database table has a corresponding "Model" that is used to interact with that table.

In addition to retrieving records from the database table, Eloquent models allow you to insert, update, and delete records from the table as well, while easily managing table relationships and data conversions.

The Active Record Pattern

Eloquent follows the Active Record architectural pattern. In Active Record, an object instance represents a single row in a database table, while the class itself represents the database table as a whole.

use App\Models\User;

// Find record by primary key (object instance represents a single row)
$user = User::find(1);

// Access columns as object properties
echo $user->name;

// Mutate and persist
$user->email = 'newemail@example.com';
$user->save();

Configuration

Eloquent is bootstrapped automatically during Lacelium's application lifecycle using the connection parameters defined in config/database.php. By default, Eloquent uses your default database connection, but you may easily query across multiple database connections:

// Using a secondary connection defined in config/database.php
$users = User::on('analytics')->where('active', 1)->get();

Key Features

  • Expressive Query Syntax: Fluent method chaining with where, orderBy, groupBy, and aggregate calculations.
  • Model Relationships: Effortlessly link models with hasOne, hasMany, belongsTo, and belongsToMany.
  • Eager Loading: Eliminate N+1 query bottlenecks using the with() method.
  • Attribute Casting: Automatically serialize and deserialize JSON, dates, booleans, and enums when reading and writing attributes.
  • Local Query Scopes: Define reusable query logic directly on your model classes.

Generating Models

To get started with Eloquent, create a model using the Dipper console:

# Generate model
php console make:model Flight

# Generate model with migration
php console make:model Flight -m

Next Steps