Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can you provide an example of eager loading with an order by condition
    Laravel eager loading order by N+1 query problem Laravel relationships Post model comments custom order by


Can you provide an example of eager loading with an order by condition


Sure, here's an example of eager loading with an order by condition in Laravel:

php
// In your controller or repository

// Eager load posts and order the comments by created_at in descending order
$posts = Post::with(['comments' => function ($query) {
    $query->orderBy('created_at', 'desc');
}])->get();

// Eager load posts and order the comments by a custom field
$posts = Post::with(['comments' => function ($query) {
    $query->orderBy('custom_field', 'asc');
}])->get();

// Eager load posts and order the comments by multiple fields
$posts = Post::with(['comments' => function ($query) {
    $query->orderBy('created_at', 'desc')
          ->orderBy('priority', 'asc');
}])->get();

The key points are:

1. Use the `with()` method to eager load the desired relationship.
2. Pass a closure to the `with()` method, which allows you to add custom conditions to the eager loaded relationship query.
3. Inside the closure, you can use the `$query` parameter to add `orderBy()` or any other query constraints you need.

This way, you can eagerly load the related models (e.g. comments) while also applying custom order by conditions to the eager loaded data. This helps avoid the N+1 query problem and allows you to fetch the data you need in a single, optimized database query.

Remember to replace `Post`, `comments`, `created_at`, `custom_field`, and `priority` with the appropriate model names, relationship names, and column names for your specific use case.

Citations:
[1] https://www.itsolutionstuff.com/post/laravel-eager-loading-tutorialexample.html
[2] https://ashallendesign.co.uk/blog/how-to-force-eager-loading-and-prevent-n-1-issues-in-laravel
[3] https://www.desarrollolibre.net/blog/laravel/eager-loading-with-conditions-in-laravel
[4] https://www.itsolutionstuff.com/post/laravel-eager-loading-with-condition-relationship-exampleexample.html
[5] https://laracasts.com/discuss/channels/laravel/eager-loading-with-condition