PHP

Efficient Eager Loading with Relationship Constraints

Optimize Laravel Eloquent N+1 issues by eagerly loading relationships while applying specific conditions to the loaded related models, improving query performance.

use App\Models\Book;

$books = Book::with(['author' => function ($query) {
    $query->where('country', 'USA');
}])->get();

foreach ($books as $book) {
    if ($book->author) {
        echo $book->title . ' by ' . $book->author->name . ' (from ' . $book->author->country . ')
';
    } else {
        echo $book->title . ' has no US author.
';
    }
}
How it works: This snippet demonstrates how to eagerly load a relationship ('author') while simultaneously applying a `where` constraint to the related model itself. Instead of just loading all authors, it only loads authors where their `country` attribute is 'USA'. This is more efficient than filtering after loading all authors and helps mitigate the N+1 query problem by fetching only relevant related data in a single query per relationship type.

Need help integrating this into your project?

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

Hire DigitalCodeLabs