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:

http://www.example.com/product/1

http://www.example.com/product/my-special-product

to bind the product model into route.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s