Laravel Route model binding with relationship

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

    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

提交回复
热议问题