DEV Community

Bijay Kumar Pun
Bijay Kumar Pun

Posted on

6 2

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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay