Search code examples
phplaravellaravel-routing

Laravel Route model binding with relationship


I am wondering if it is possible to return a relationship with laravels Route model binding ?

Say is a have a user model with a relationship 'friends' to other users, and I want to return both the user info and the relationship from a route or controller.

eg for the route domain.tld/user/123

Route::model('user', 'User');

Route::get('/user/{user}', function(User $user) {

    return Response::json($user);

});

this will return me the user info fine but I also want the relationships, is there any easy/proper way to do this ?

I know I can do this

Route::get('/user/{user}', function((User $user) {

    return Response::json(User::find($user['id'])->with('friends')->get());

});

or

Route::get('/user/{id}', function(($id) {

   return Response::json(User::find($id)->with('friends')->get());

});

but I suspect there may be a better way.


Solution

  • You can populate the $with property in the User model. Like so;

    protected $with = ['friends'];
    

    This will autoload the relationship data for you automatically.

    Please Note: This will do it for every user model query.

    If you dont want friends to be loaded all the time, then you can bind it to the parameter within your route, like so;

    Route::bind('user_id', function($id) {
        return User::with('friends')->findOrFail($id);
    });
    
    Route::get('/user/{user_id}', 'BlogController@viewPost');