Laravel Route model binding with relationship

后端 未结 3 1504
后悔当初
后悔当初 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:06

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

提交回复
热议问题