Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Route model binding with relationship

Tags:

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, and I want to return both the user info and the relationship from a route or controller.

eg for the 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 info fine but I also want the relationships, is there any easy/proper way to do this ?

I know I can do this

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

like image 413
Keith Avatar asked Nov 12 '14 13:11

Keith


People also ask

How does Laravel route model binding work?

Laravel route model binding provides a convenient way to automatically inject the model instances directly into your routes. For example, instead of injecting a user's ID, you can inject the entire User model instance that matches the given ID.

What is prefix in Laravel route?

Path prefixes are used when we want to provide a common URL structure. We can specify the prefix for all the routes defined within the group by using the prefix array option in the route group.

How pass data from controller route in Laravel?

You can pass data to route in laravel using different ways. First, you have to define a web route with parameters and after that, you can pass data to the web route by calling the route method to anchor tag and HTML form attribute.

What is the benefit of named routes in Laravel?

Named routing is another amazing feature of Laravel framework. Named routes allow referring to routes when generating redirects or Urls more comfortably. You can specify named routes by chaining the name method onto the route definition: Route::get('user/profile', function () { // })->name('profile');


1 Answers

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'));     } } 
like image 94
Martin Bean Avatar answered Sep 23 '22 17:09

Martin Bean