Last updated on February 17, 2018
Laravel’s route model binding has been around for a while, but Laravel 5.2 is about to make it even easier with Implicit model binding. Implicit model binding makes it painless to inject relevant models directly into your routes and controllers.
Implicit model binding gives the benefits of route model binding without having to define anything in the Route Service Provider.For example, in 5.1 we used to do something like following –
// RouteServiceProvider.php Route::bind('user', function($value) { return App\User::find($value); }); //Route.php Route::get('/users/{user}', function(App\User $user) { dd($user)); });
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.
For example, assume you have a route or controller defined like the following in your laravel5.2 application:
Route – Implicit model binding
use App\User; Route::get('/user/{user}', function (User $user) { return $user; });
Controllers- Implicit model binding
In Laravel 5.2, the framework will automatically inject this model based on the URI segment, allowing you to quickly gain access to the model instances you need. As you know in Laravel 5.1, you need to use the
Route::model
orRoute::bind
method to achieve same results.Laravel will automatically inject the model when the route parameter segment ({user}) matches the route Closure or controller method's corresponding variable name ($user) and the variable is type-hinting an Eloquent model class.
NOTE: Route parameter segment ({user}) and variable name ($user) should be same otherwise it will not work.
Now point your browser to
http://hostname/user/id
you will get single user object. behind the scene laravel callsfindOrfail()
method on the modal object. By default Laravel uses "id", instead of ID if you want to use any other column you can do it by extendingIlluminate\Contracts\Routing\UrlRoutable
.Eloquent implements the
Illuminate\Contracts\Routing\UrlRoutable
contract, which means every Eloquent object has agetRouteKeyName()
method on it that defines which column should be used to look it up from a URL. You can override that on any Eloquent model as shown below// User.php class User extends Model { public function getRouteKeyName() { return 'username'; } }//you can also do following -
RouteServiceProvider.php Route::bind('user',function($username){ User::where('username',$username)->findOrfail(); });