Advanced Eloquent Techniques

πŸ“˜ Laravel πŸ‘ 33 views πŸ“… Dec 22, 2025
⏱ Estimated reading time: 2 min

Eloquent ORM provides powerful features beyond basic CRUD operations. Advanced Eloquent techniques help developers write efficient, expressive, and optimized database queries while keeping code clean and maintainable.


1. Query Scopes

Local Scopes

Local scopes allow reusable query logic inside models.

public function scopeActive($query) { return $query->where('status', 'active'); }

Usage:

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

Global Scopes

Global scopes automatically apply constraints to all queries.

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

2. Eager Loading and Lazy Loading

Eager Loading (Performance Optimization)

Preloads relationships to avoid N+1 query problem.

Post::with('comments')->get();

Lazy Loading

Loads relationships only when accessed.

$post->comments;

3. Conditional Relationships

Load relationships conditionally:

Post::with(['comments' => function ($query) { $query->where('approved', true); }])->get();

4. Attribute Casting

Automatically convert attributes to specific types.

protected $casts = [ 'is_active' => 'boolean', 'published_at' => 'datetime', ];

5. Accessors and Mutators

Accessors (Format Data When Reading)

public function getFullNameAttribute() { return $this->first_name . ' ' . $this->last_name; }

Usage:

$user->full_name;

Mutators (Modify Data Before Saving)

public function setPasswordAttribute($value) { $this->attributes['password'] = bcrypt($value); }

6. Model Events

Listen to model lifecycle events:

protected static function booted() { static::creating(function ($model) { $model->uuid = Str::uuid(); }); }

Events include:

  • creating

  • created

  • updating

  • updated

  • deleting

  • deleted


7. Soft Deletes

Instead of permanently deleting records:

use Illuminate\Database\Eloquent\SoftDeletes; class Post extends Model { use SoftDeletes; }

Migration:

$table->softDeletes();

Retrieve trashed records:

Post::withTrashed()->get();

8. Relationship Methods

hasManyThrough

public function posts() { return $this->hasManyThrough(Post::class, Comment::class); }

Polymorphic Relationships

public function imageable() { return $this->morphTo(); }

9. Subqueries

User::whereIn('id', function ($query) { $query->select('user_id')->from('posts'); })->get();

10. Chunking Large Datasets

Process large datasets efficiently:

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

11. Upserts

Insert or update records in one operation:

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

12. Custom Pivot Models

class RoleUser extends Pivot { protected $table = 'role_user'; }

Conclusion

Advanced Eloquent techniques empower developers to write powerful, efficient, and scalable database interactions. By mastering scopes, relationships, events, and performance optimizations, you can fully leverage Laravel’s ORM while keeping your application clean and maintainable.


πŸ”’ Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes