How to chain eloquent relation in route in laravel?

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

How to chain eloquent relation in route in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dana , a month 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.