Eloquent ORM

Print Print
Reading time 1:6

Eloquent is the object-relational mapper (ORM) built into the Laravel framework. It lets you interact with database tables using PHP classes and objects instead of writing raw SQL, following the active record pattern where each database table has a corresponding "Model" that is used to interact with that table.

Defining a Model

Models typically live in the app/Models directory and extend Laravel's base Model class. By convention, Eloquent assumes a model called Post maps to a table named posts, but this can be overridden with the $table property.

Example model

class Post extends Model
{
    protected $fillable = ['title', 'body'];
}

Querying Records

Once a model is defined, Eloquent provides a fluent query builder for reading and writing data:

Basic queries

$posts = Post::where('published', true)->orderBy('created_at', 'desc')->get();
$post = Post::find(1);
Post::create(['title' => 'Hello', 'body' => 'World']);

Relationships

Eloquent supports common relationship types, including one-to-one, one-to-many, many-to-many, and polymorphic relations, defined as methods on the model that return relationship objects such as hasMany or belongsTo.

Mass Assignment Protection

To guard against unintended data changes, models define either a $fillable array (an allow-list of attributes that can be mass assigned) or a $guarded array (a deny-list). Attempting to mass assign a non-fillable attribute is silently ignored unless strict mode is enabled.

By: Tomas Silny
Edited: 2026-08-13 03:31:17