php - Laravel Route model binding with relaionship -
i wondering if possible return relationship laravels route model binding ?
say have user model relationship 'friends' other users, , want return both user info , relationship route or controller.
eg route domain.tld/user/123
route::model('user', 'user'); route::get('/user/{user}', function(user $user) { return response::json($user); });
this return me user info fine want relationships, there easy/proper way ?
i know can
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 suspect there may better way, in advance
keith
you can populate $with
property in user model. so;
protected $with = ['friends'];
this autoload relationship data automatically.
please note: every user model query.
if dont want friends loaded time, can bind parameter within route, so;
route::bind('user_id', function($id) { return user::with('friends')->findorfail($id); }); route::get('/user/{user_id}', 'blogcontroller@viewpost');
Comments
Post a Comment