PHP

Efficiently Loading Related Models with Eager Loading Constraints

Optimize database queries by eagerly loading only specific related models or filtered relationships to solve the N+1 problem and improve performance in Laravel Eloquent.

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function index()
    {
        // Load posts and their comments, but only comments that are approved.
        $posts = Post::with(['user', 'comments' => function ($query) {
            $query->where('approved', true)->orderBy('created_at', 'desc');
        }])->get();

        return view('posts.index', compact('posts'));
    }
}

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

//     public function comments()
//     {
//         return $this->hasMany(Comment::class);
//     }
// }
How it works: This snippet demonstrates how to use eager loading with constraints to fetch related data efficiently. The `with()` method prevents the N+1 query problem by loading all related records in a single query. By passing a closure to `with()`, you can add specific query constraints to the related model, such as filtering comments by their 'approved' status. This ensures you only load the necessary data, significantly improving performance for complex relationships and large datasets.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs