Laravel Route model binding with relationship
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');
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'));
}
}