DEV Community

Bijay Kumar Pun
Bijay Kumar Pun

Posted on

Route Model Binding in Laravel

Route Model Binding provides a mechanism to bind/inject a model instance in the route. It's a neat way to validates a model Id injected in the route by injecting a Model instance.

Implicit Binding
In this method, we directly inject the model instance by passing the type hinted variable as a parameter in the closure. The type hinted variable name should match the route segment name.

Route::get('api/posts/{post}',function(App\Post $post){
return $post->title;
});
Enter fullscreen mode Exit fullscreen mode

Here, the {post} URI segment in the URL matches the type hinted $post variable.
Laravel will then automatically inject the model instance that has an id field matching the corresponding value from the request URI, i.e {post}, if not matched a 404 HTTP response will be automatically generated.

In default case the default column looked for is the id column but can be changed by using the getRouteKeyName() Eloquent function.

public function getRouteKeyName(){
return 'slug';
}
Enter fullscreen mode Exit fullscreen mode

Now the route will have slug instead of id.

Explicit Binding
In this method, we explicitly bind a model to the segment of the route.

Explicit binding can be done by using Router::model() method. This can be used inside boot() method of RouterServiceProvider class.

//RouteServiceProvider.php
public function boot(){
parent::boot();
Route::model('post',App\Post::class);
}
Enter fullscreen mode Exit fullscreen mode

This bounds all {post} parameters to the App\Post model, meaning a Post model will then be injected in the route.

The difference between implicit and explicit binding is explicit binding allows putting extra logic.

Another way of explicit binding is by overriding resolveRouteBinding() method on the Eloquent model itself.

//App\Post model
public function resolveRouteBinding($value)
{return $this->where('slug',$value)->first()??abort(404);
}
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
vijaykanaujia profile image
vijay kanaujia

informative, thanks

Collapse
 
upkareno profile image
mohamed mostafa

Thanks

Collapse
 
coding_forest profile image
coding forest

Very helpful