Laravel Route model binding with relationship

后端 未结 3 1503
后悔当初
后悔当初 2021-02-02 13:31

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,

3条回答
  •  一向
    一向 (楼主)
    2021-02-02 14:08

    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');
    

提交回复
热议问题