Laravel Eloquent ORM Reference Guide

A reference guide to Laravel's Eloquent ORM: models, relationships, eager loading, and query scopes.

Eloquent is Laravel's ORM. It follows the active record pattern: each database table has a matching model class, and each model instance is one row, which you read, change and save through the model rather than by writing SQL by hand. The examples below target Laravel 11 and 12, were run against Laravel 12, and assume a model such as App\Models\Post backed by a posts table.

Defining a model

Eloquent models sit on top of the same query builder covered elsewhere — every method shown below (where(), orderBy(), and so on) is available on a model just as it is on DB::table().

php artisan make:model Post -m   // -m also creates a migration

See the database field types guide for the column types and modifiers available inside that migration.

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

    protected $hidden = ['internal_notes'];

    protected $casts = [
        'published_at' => 'datetime',
        'is_featured' => 'boolean',
        'metadata' => 'array',
    ];
}

$fillable whitelists which attributes can be mass-assigned via create()/fill() — the counterpart $guarded blacklists instead. Setting protected $guarded = [] allows every attribute (rely on this only when input is already validated elsewhere, since it removes the whitelist entirely). $hidden excludes attributes when the model is converted to an array or JSON. $casts converts attributes to native types (or Carbon instances for dates) automatically — pasting a cast attribute's raw JSON into the JSON viewer is a quick way to check its structure before writing a cast. Laravel 11 and later also accept the same map from a protected casts(): array method, which is handy when a cast needs a method call rather than a constant; both forms work. A native PHP enum also works directly as a cast ('status' => PostStatus::class), and for anything more involved than a type conversion, a custom cast class implementing CastsAttributes can encapsulate arbitrary get/set logic (e.g. an encrypted cast, built in for exactly that).

Basic CRUD

Post::create(['title' => 'Hello', 'body' => '...']);

Post::find(1);
Post::findOrFail(1);
Post::where('published', true)->first();
Post::all();

$post = Post::find(1);
$post->title = 'Updated title';
$post->save();

Post::where('id', 1)->update(['title' => 'Updated title']);

$post->delete();
Post::destroy([1, 2, 3]);

all() and other multi-row queries return a Collection, not a plain array, so the result is immediately chainable with map, filter, pluck, and the rest.

One difference between the two update styles: $post->save() works on a loaded model and fires its model events (and any observers), while Post::where(...)->update([...]) is a single SQL statement that never loads the models, so the saving/updated events don't fire. The same applies to a mass delete().

// Find by attributes, or create with the merged attributes if none exists
Post::firstOrCreate(['slug' => 'hello-world'], ['title' => 'Hello World']);

// Same lookup, but update the matched row (or create it) either way
Post::updateOrCreate(['slug' => 'hello-world'], ['title' => 'Hello World']);

// Like firstOrCreate but doesn't persist — useful when you want to set more before saving
$post = Post::firstOrNew(['slug' => 'hello-world']);

firstOrCreate only writes to the database when nothing matches. updateOrCreate fills the matched row with the new values and saves it, which issues an UPDATE only if something actually changed. Neither is atomic on its own: two simultaneous requests can both miss the lookup. Back the lookup columns with a unique index and current Laravel 12 releases recover from the resulting violation by re-reading the existing row; createOrFirst() does this directly, trying the insert first and falling back to a select, which suits the case where the row usually doesn't exist yet. Without that index you can still end up with duplicates.

Relationships

class User extends Model
{
    public function posts(): HasMany
    {
        return $this->hasMany(Post::class);
    }

    public function profile(): HasOne
    {
        return $this->hasOne(Profile::class);
    }

    public function roles(): BelongsToMany
    {
        return $this->belongsToMany(Role::class);
    }
}

class Post extends Model
{
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function comments(): MorphMany
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}
RelationshipMeaning
hasOneThis model owns exactly one related row (e.g. User → Profile).
hasManyThis model owns many related rows (e.g. User → Posts).
belongsToThe inverse — this model holds the foreign key (e.g. Post → User).
belongsToManyMany-to-many via a pivot table (e.g. User ↔ Role).
hasManyThroughAccess a distant relation through an intermediate model.
morphMany / morphToPolymorphic relationship — one relation type serving several model types.

Pivot tables for belongsToMany can carry their own columns beyond the two foreign keys: withPivot('assigned_at') makes that column available on $user->roles->first()->pivot->assigned_at, and withTimestamps() maintains created_at/updated_at on the pivot row itself. wherePivot('assigned_at', '>', now()->subMonth()) filters the relation query by a pivot column. A $touches = ['post'] property on a child model (e.g. Comment) updates the parent's updated_at whenever the child is saved — handy for cache-busting a parent based on its children changing.

Eager loading (avoiding N+1)

Accessing $post->user in a loop over many posts fires one extra query per post. Eager load the relationship up front instead:

// N+1: fires a query per post inside the loop
foreach (Post::all() as $post) {
    echo $post->user->name;
}

// One extra query total, not one per post
$posts = Post::with('user')->get();

$posts = Post::with(['user', 'comments'])->get();

// Load a relation on an already-fetched collection
$posts->load('comments');

N+1 problems are easy to introduce accidentally — a relation accessed inside a Blade @foreach, or inside an API resource's toArray(), looks identical to any other property access, so nothing warns you at the call site. Model::preventLazyLoading(), usually called in AppServiceProvider::boot() for the local environment, throws an exception the moment code lazy-loads a relationship instead of eager-loading it, which surfaces these during development rather than as a slow endpoint in production. For counting related rows without loading them at all, withCount('comments') adds a comments_count attribute using a single aggregate subquery.

// Constrain what gets eager loaded
$posts = Post::with(['comments' => fn ($query) => $query->where('approved', true)])->get();

// Nested relationships, with dot notation
$posts = Post::with('comments.user')->get();

// Only some columns — always include the key Eloquent matches on
$posts = Post::with('user:id,name')->get();

// Load only what isn't already loaded
$posts->loadMissing('comments');

When you select columns on an eager-loaded relation, include its primary key (id) and any foreign key. Without them Eloquent can't match the related rows back to their parents and the relation comes back empty. Recent Laravel 12 releases can also remove many N+1 problems automatically: calling Model::automaticallyEagerLoadRelationships() in AppServiceProvider::boot() makes Eloquent eager load a relation for the whole collection the first time one model in it is lazy-loaded. It's a useful safety net, but an explicit with() keeps the queries visible where you read the code.

Query scopes

class Post extends Model
{
    public function scopePublished(Builder $query): void
    {
        $query->where('published', true);
    }
}

Post::published()->latest()->get();

That's a local scope — opt-in, called explicitly. A global scope applies to every query against the model automatically, the same way soft deletes silently exclude trashed rows:

class PublishedScope implements Scope
{
    public function apply(Builder $builder, Model $model): void
    {
        $builder->where('published', true);
    }
}

class Post extends Model
{
    protected static function booted(): void
    {
        static::addGlobalScope(new PublishedScope);
    }
}

Post::all();                          // published rows only, no explicit filter needed
Post::withoutGlobalScope(PublishedScope::class)->get();   // opt out for this query

Because a global scope is invisible at the call site, reach for it sparingly — it's easy to forget it's filtering results when debugging "missing" rows later.

Laravel 12 also lets you declare these with attributes. A local scope marked #[Scope] doesn't need the scope prefix and is called the same way (Post::published()), and #[ScopedBy([PublishedScope::class])] on the model class registers a global scope without a booted() method:

use Illuminate\Database\Eloquent\Attributes\Scope;

#[Scope]
protected function published(Builder $query): void
{
    $query->where('published', true);
}

Chunking large result sets

get()/all() load every matching row into memory at once. For a table too large for that, process it in batches instead:

Post::chunk(200, function ($posts) {
    foreach ($posts as $post) {
        // ...
    }
});

// Safer when the callback updates/deletes rows in the chunk being iterated —
// chunk() re-runs the same offset query each time and can skip/repeat rows otherwise
Post::chunkById(200, function ($posts) {
    foreach ($posts as $post) {
        $post->update(['processed' => true]);
    }
});

// A generator over the whole table with one row in memory at a time —
// usable directly with foreach, no callback needed
foreach (Post::lazy() as $post) {
    // ...
}

// The same safety as chunkById(), as a lazy collection
Post::where('processed', false)
    ->lazyById(200)
    ->each(fn ($post) => $post->update(['processed' => true]));

chunk() and lazy() page through the results with an offset, so updating the column you're filtering on shifts the remaining rows and later pages skip some of them. chunkById() and lazyById() continue from the last id instead. They add their own where condition, so wrap any orWhere of your own in a closure to keep it grouped.

Common performance problems

  • N+1 queries. A relation read inside a loop runs one query per row. Eager load it with with(), and call Model::preventLazyLoading() in development to catch the rest.
  • Loading rows just to count them. $post->comments->count() fetches every comment first. $post->comments()->count() or exists() runs a single COUNT or EXISTS query, and withCount() does it for a whole list.
  • Selecting every column. Post::select('id', 'title')->get() or pluck('title', 'id') is lighter than hydrating full models, especially with large text columns. Keep the key-column rule for eager-loaded relations in mind.
  • Loading a whole table into memory. Use chunkById() or lazyById() for batch work, as above.
  • Missing indexes. Eloquent can't make an unindexed where, join or sort fast. Index the columns you filter and order by — the field types guide covers index and foreign key modifiers in migrations.
  • Doing the work in PHP. Summing or filtering a loaded collection transfers every row; Post::sum('views'), where() and withSum() let the database do it. Reach for the query builder directly when a report needs joins or aggregates that models only get in the way of.

Accessors and mutators

use Illuminate\Database\Eloquent\Casts\Attribute;

class User extends Model
{
    protected function fullName(): Attribute
    {
        return Attribute::make(
            get: fn () => "{$this->first_name} {$this->last_name}",
            set: function (string $value) {
                [$first, $last] = array_pad(explode(' ', $value, 2), 2, null);

                return ['first_name' => $first, 'last_name' => $last];
            },
        );
    }
}

$user->full_name;                  // uses the get callback
$user->full_name = 'Ada Lovelace'; // the set callback fills both columns

A setter that returns an array sets several attributes at once, as above; return a single value and it is stored on the attribute the accessor is named after. Returning only one of the pieces would silently drop the rest.

Soft deletes

Adding the SoftDeletes trait means delete() sets a deleted_at timestamp instead of removing the row, and every query automatically excludes soft-deleted records without you having to remember to filter them out. The model needs a nullable deleted_at column, typically added with $table->softDeletes() in a migration — see the database field types guide for that column type.

class Post extends Model
{
    use SoftDeletes;
}

$post->delete();          // sets deleted_at, row stays in the table
Post::find(1);             // null — soft-deleted rows are excluded by default

Post::withTrashed()->find(1);   // include soft-deleted rows
Post::onlyTrashed()->get();     // only soft-deleted rows
$post->restore();               // clear deleted_at
$post->forceDelete();           // actually remove the row

Soft deletes are worth using whenever "deleted" data still has audit, undo, or reporting value — but every relationship touching that model needs to account for it, since a soft-deleted parent's children don't get soft-deleted automatically, and unique constraints in the database won't know to ignore trashed rows either.

Factories and seeders

Factories describe how to generate a fake but realistic instance of a model, which is invaluable for tests and for populating a local database with representative data instead of hand-writing rows.

php artisan make:factory PostFactory
php artisan make:seeder PostSeeder
class PostFactory extends Factory
{
    public function definition(): array
    {
        return [
            'title' => fake()->sentence(),
            'body' => fake()->paragraphs(3, true),
            'user_id' => User::factory(),
        ];
    }
}

Post::factory()->count(20)->create();
Post::factory()->create(['title' => 'Fixed title']);

// A named state for a common variation
Post::factory()->count(5)->published()->create();

Seeders drive factories (or insert fixed reference data) and are run with php artisan db:seed, or automatically as part of php artisan migrate:fresh --seed when rebuilding a local database from scratch. See the Artisan commands guide for more on make: generators and running commands.

Models rarely work alone. The query builder underlies every Eloquent query, collections are what multi-row results come back as, and the database field types guide covers the migrations behind them. Policies authorize what a user can do with a model, API resources shape models into JSON, and the testing guide shows factories in feature tests. The official Eloquent documentation covers everything not listed here.