Posted in Laravel, PHP

Implicit Model Binding : Changing Model’s Route Key

When using Implicit Model Binding, the model can be fetched using the id parameter by default. Consider when you need to list product details for an id, you use:

Route::get('product/{id}', 'ContactsController@index');

and in controller:

public function index(Product $id) 
{
        // Some activity here
}

Now you can access http://www.example.com/product/1

Suppose, when you need to search using slug for product or any other unique key like http://www.example.com/product/my-special-product which is SEO friendly, you can add

class Product extends Model 
{ 
      public function getRouteKeyName() 
      { 
           return 'slug'; 
      } 
}

in Product model. Now, you are overriding getRouteKeyName function of Eloquent model

Advertisements

One thought on “Implicit Model Binding : Changing Model’s Route Key

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