Laravel model binding model with binding

I am wondering if it is possible to return a link to laravels with a route model binding?

Let's say a user has a model with friendships with other users, and I want to return both user information and relationships with a route or controller.

e.g. for 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 information in order, but I also want a relationship, is there a simple / correct way to do this?

i know i can do it

 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 might be a better way.

+7
source share
2 answers

You can populate the $with property in the user model. Thus,

 protected $with = ['friends']; 

This will automatically download the relationship data.

Note: This will do this for each user-specific model request.

If you do not want friends to load all the time, you can bind it to a parameter in your route, for example:

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

You don’t want the relationship to be eagerly loaded for every request, such as Matt Burrow , just to be available in one context. It is inefficient.

Instead, in your controller action, you can load on-demand relationships when you need them. Therefore, if you use the route model binding to provide a User instance for your controller action, but you also want a friends relation, you can do this:

 class UserController extends Controller { public function show(User $user) { $user->load('friends'); return view('user.show', compact('user')); } } 
+6
source

Source: https://habr.com/ru/post/1206719/


All Articles