Posted in Laravel, PHP

Route Model Binding : Multiple Route Key

When using Implicit Model Binding, you can use getRouteKeyName  to use alternative column such as slug instead of id to inject a model instance directly inside routes. Now, model can be bound only with slug column. When you think to use id, the binding fails. If there is a situation arises where you need to use both id and slug column to bind the model, you need an alternative way:

You can use Explicit Binding by adding the following in the boot method of the RouteServiceProvider class:

Route::bind('product', function($value) {
     return \App\Product::where('id', $value)->orWhere('slug', $value)->first();

Now, it is possible to use both:

to bind the product model into route.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s