How to chain eloquent relation in route in laravel?

by mallory_cormier , in category: PHP Frameworks , a year ago

How to chain eloquent relation in route in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dana , a year ago

@mallory_cormier 

You can chain Eloquent relations in your routes in Laravel by using the with method.


For example, if you have a User model with a posts relation and each post has a comments relation, you can eager load the posts and comments in your route like this:

1
2
3
4
5
Route::get('users', function () {
    $users = User::with('posts.comments')->get();

    return $users;
});


This will eager load the posts relation for each user and then eager load the comments relation for each post. This is more efficient than lazy loading because it reduces the number of queries made to the database.

Related Threads:

How to join 3 tables using laravel eloquent?
How to chain with clauses in laravel?
How to dynamically chain a function in laravel?
How to put schedule task jobs in chain in laravel?
How to get a all eloquent models in laravel?
How to render all data in relation in laravel?