A Practical Guide to Laravel Eloquent for Intermediate Developers

Laravel Eloquent is more than just a simple ORM. If you already know the basics like find, create, and simple relationships, this post will take you deeper into what makes Eloquent powerful. We will explore intermediate level features with examples and explanations in clear non native English.


1. Query Scopes for Clean and Reusable Queries

Scopes help you define custom logic that you can reuse across the application.

Global Scope

Add global rules to all queries of a model.

protected static function booted() {
    static::addGlobalScope('active', function ($builder) {
        $builder->where('status', 'active');
    });
}

Now every query on the model will apply this automatically.

Local Scope

Reusable filter for specific queries.

public function scopeRecent($query) {
    return $query->orderBy('created_at', 'desc');
}

User::recent()->get();

2. Advanced Eager Loading

Avoid N plus 1 problem by eager loading with conditions.

$users = User::with(['posts' => function ($query) {
    $query->where('published', true);
}])->get();

Use nested eager loading:

$users = User::with('posts.comments')->get();

Count related models efficiently:

$users = User::withCount('posts')->get();

3. Dynamic Relationships

You can define relationships at runtime using Relation::morphMap() or inline definitions.

$user = new User();
$user->setRelation('latestPost', Post::latest()->first());

This helps when loading computed relationships in APIs without modifying the model class.


4. Chunking and Cursors for Big Data

When working with large data sets avoid using get() directly.

Chunking

User::chunk(100, function($users) {
    foreach ($users as $user) {
        // process user
    }
});

Cursor

foreach (User::cursor() as $user) {
    // memory efficient
}

5. Mutators and Casts with Data Transformation

In Laravel 10 and up use modern mutator syntax.

public function casts(): array {
    return [
        'options' => 'array',
        'is_active' => 'boolean',
        'birthday' => 'date:Y-m-d'
    ];
}

You can also define custom casts:

class JsonCast implements CastsAttributes {
    public function get($model, $key, $value, $attributes) {
        return json_decode($value);
    }

    public function set($model, $key, $value, $attributes) {
        return json_encode($value);
    }
}

In model:

protected $casts = [
    'settings' => JsonCast::class,
];

6. Model Observers

If you have logic that needs to run during model events like created or deleted use observers.

php artisan make:observer UserObserver

In UserObserver.php

public function created(User $user) {
    // send welcome email
}

Register in AppServiceProvider

User::observe(UserObserver::class);

7. Polymorphic and Many to Many Relationships

Polymorphic

A comment can belong to either a post or video.

class Comment extends Model {
    public function commentable() {
        return $this->morphTo();
    }
}

Many to Many with Pivot Data

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

You can now access:

$user->roles->first()->pivot->assigned_by;

8. Relationship Events and Touching

If a post changes and you want to update the updated_at of the user:

protected $touches = ['user'];

This is useful for cache invalidation or syncing changes.


9. Upserts and FirstOr

Upsert

Insert or update in bulk

User::upsert([
    ['email' => 'a@example.com', 'name' => 'A'],
    ['email' => 'b@example.com', 'name' => 'B'],
], ['email'], ['name']);

FirstOrCreate

User::firstOrCreate(['email' => 'a@example.com'], ['name' => 'John']);

10. Using API Resources with Eloquent

Clean API responses using resources.

php artisan make:resource UserResource

Then use it:

return new UserResource($user);

You can control exactly what fields are returned. It works well with relationships and pagination too.


Summary

Laravel Eloquent is not just for beginners. It gives you many advanced tools to build scalable and clean applications. By learning scopes casting events observers and polymorphic relations you become more productive and keep your code DRY and readable.

Keep practicing and explore the official documentation for new improvements in Laravel 10 11 and 12. Eloquent is always evolving.

Let me know if you want to go even deeper into custom collections macros performance tuning or writing service layers with Eloquent.

0
Subscribe to my newsletter

Read articles from Rameez Karamat Bhatti directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Rameez Karamat Bhatti
Rameez Karamat Bhatti

I am a full-stack developer currently working with PHP, Laravel, Tailwind CSS, and Livewire. I also work extensively with Inertia.js to build seamless single-page applications using Vue.js and Laravel. I have experience building reactive frontends with Vue.js and React, and robust backends with REST APIs. I am highly proficient in MySQL, MongoDB, and also comfortable working with PostgreSQL for relational data projects. My focus is on clean, scalable code and building user-focused digital products.