Laravel Route model binding with relationship

走远了吗. 提交于 2019-12-03 05:49:43

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

You don’t want to eager-load relationships on every query like Matt Burrow suggests, just to have it available in one context. This is inefficient.

Instead, in your controller action, you can load relationships “on demand” when you need them. So if you use route–model binding to provide a User instance to your controller action, but you also want the friends relationship, you can do this:

class UserController extends Controller
{
    public function show(User $user)
    {
        $user->load('friends');

        return view('user.show', compact('user'));
    }
}

Martin Bean's response is probably not the way you want to tackle this, only because it introduces an n+1 to your Controller:

1) It must load the User via Route Model Binding, then....

2) It now loads the relationship for friends

He is correct, however, that you probably don't want to load the relationship every time.

This is why Matt Burrow's solution is probably better (he's binding a different value: instead of {user}, you could use something like {user_with_friends} and bind that separately from {user}...

Personally, I think if you need to load friends for only that route, I'd simply just pass $userId (without binding), and just begin the controller method with:

$user = User::with('friends')->findOrFail($userId);

You can either let Laravel handle the ModelNotFoundException automatically (like it does with Route Model Binding), or wrap it in a try/catch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!