Reputation: 171
What is Route Binding
in laravel. Why we using this. Can you please explain me in simple words.
Upvotes: 1
Views: 455
Reputation: 6351
The following is the detail given for route model binding on Laravel's website which I think is pretty simple to understand.
Laravel model binding provides a convenient way to inject class instances into your routes. For example, instead of injecting a user's ID, you can inject the entire User class instance that matches the given ID.
First, use the router's model method to specify the class for a given parameter. You should define your model bindings in the RouteServiceProvider::boot method:
Binding A Parameter To A Model
public function boot(Router $router)
{
parent::boot($router);
$router->model('user', 'App\User');
}
Next, define a route that contains a {user} parameter:
Route::get('profile/{user}', function(App\User $user)
{
//
});
Since we have bound the {user} parameter to the App\User model, a User instance will be injected into the route. So, for example, a request to profile/1 will inject the User instance which has an ID of 1.
If you wish to specify your own "not found" behavior, pass a Closure as the third argument to the model method:
Route::model('user', 'User', function()
{
throw new NotFoundHttpException;
});
If you wish to use your own resolution logic, you should use the Route::bind method. The Closure you pass to the bind method will receive the value of the URI segment, and should return an instance of the class you want to be injected into the route:
Route::bind('user', function($value)
{
return User::where('name', $value)->first();
});
A detailed instructions over routing can be found on this link to Laravel docs.
Upvotes: 2
Reputation: 4020
Here are two links that will give you some rough idea:
Or else, what @KhanShahrukh has given the solution should solve your doubt.
Upvotes: 0