Aziz Bhatti
Aziz Bhatti

Reputation: 53

What does Route::model mean in Laravel?

Can any one explain these lines ? How it works?

public function boot()
{
     parent::boot();

     Route::model('user', App\User::class);
}

Next, define a route that contains a {user} parameter:

$router->get('profile/{user}', function(App\User $user) {
  //
});

Upvotes: 4

Views: 2217

Answers (1)

Moppo
Moppo

Reputation: 19285

This is called Route Model Explicit Binding

With this:

Route::model('user', App\User::class);

you're saying: when a 'user' string is used in a route as a parameter, create a model of App\User::class for me, that has the same id as the parameter passed to the route. Then inject the model on the route method handler.

For example, the url: 'profile/10' will match this route:

$router->get('profile/{user}', function(App\User $user) {
  //
});

And the App\User model with an id of 10 will be automatically fetched by Laravel

From a general point of view, normally in your routes you do something like this:

public function edit($id)
{
    //fetch the user from db...
    $user = User::find($id);

    //do something with the $user...
}

with Route Model Binding you can do:

public function edit(App\User $user)
{
    //do something with $user...
}

avoiding to fetch the model from the database: Laravel will do it for you

Upvotes: 5

Related Questions