Laravel: Resource Controller change parameter from ID to Slug Laravel: Resource Controller change parameter from ID to Slug laravel laravel

Laravel: Resource Controller change parameter from ID to Slug


For Resource Routing the route parameter is the resource name, first argument, in singular form.

Route::resource('categories', 'CategoryController');

Will give you a route parameter of category. You can see this by running php artisan route:list and looking at the routes that are defined.

If you want to use a different parameter name for a resource you can also do that by overriding the parameter:

Route::resource('categories', 'CategoryController')->parameters([    'categories' => 'something',]);

Now the route parameter used would be something.

This only has to do with the route parameter name, it has nothing to do with how any binding would be resolved, unless you had an Explicit Route Model Binding defined specifically for a parameter name.

If you are using Implicit Route Model Bindings you would define on your Model itself what field is used for the binding via the getRouteKeyName method. [In the next version of Laravel you will be able to define the field used in the route definition itself.]

Laravel 6.x Docs - Controllers - Resource Controllers - Naming Resource Parameters

Laravel 6.x Docs - Routing - Model Bindings - Implicit Route Model Binding getRouteKeyName


This can also be achieved by changing the customizing the key. In here slug refers to a column in the Category model.

Route::resource('categories', 'CategoryController')->parameters([    'categories' => 'categories:slug',]);