Laravel 5.6 additional Route::resource() Parameters

Ricky picture Ricky · Apr 17, 2018 · Viewed 14.3k times · Source

I would like to know how to add additional parameters to Laravel's Route Resource without using Query Strings.

I created a controller (CustomerController) with all the built-in resources and then, added the following route:

Route::resource('customers', 'CustomerController');

What i would like to do is add additional parameters to some of the default resources without creating custom routes or using query strings. For example:

Default resource with optional parameter (index):

public function index($page = 0)
{
    //...
}

Desired URL:

http://www.example.com/customers
http://www.example.com/customers/{page}

I tried the following, but i get a not found exception (NotFoundHttpException):

Route::resource('customers', 'CustomerController')->parameters([
    'index' => 'page'
]);

Is this possible? If so, how can i accomplish it?

Answer

sam picture sam · Apr 17, 2018

Resource Controllers must implement a defined set of methods which are then mapped to the appropriate HTTP verb and path by the router. These methods, paths and verbs form part of a contract that cannot be adjusted, otherwise working with a Laravel application that implements Resource Controllers would be a headache.

Resource Controllers excel in providing the same experience across all Laravel applications, if your application requires behaviour that isn't supported out of the box by Resource Controllers then it is a sign that you should not be using them and should instead register your routes manually.

If you have just one route that needs to implement custom behaviour then you can register some methods instead of all and then choose to register a custom route to your Resource Controllers method, something like:

Route::resource('customers', 'CustomerController')->except([
    'index'
]);

Route::get('/customers/{page?}', 'CustomerController@index');

The documentation on Resource Controllers covers except and only.