Laravel Routes same base path

Viewed 177

On Larave 7, I have routes with same path prefix :

    /*
    |--------------------------------------------------------------------------
    | Parking Routes
    |-------------------------------------------------------------------------- */
    Route::resource('parkings', 'Api\Parking\ParkingController');
    Route::get('parkings/filters', 'Api\Parking\ParkingFilterController');

In this way, parkings/filters returns 404 error.

If I invert the order of the routes :

    Route::get('parkings/filters', 'Api\Parking\ParkingFilterController');
    Route::resource('parkings', 'Api\Parking\ParkingController');

It works correctly, but is there a way to do something cleaner ? Like limit parkings route ?

1 Answers

Your issue comes from the fact that your resourceful controller uses a GET route parkings/{parking} which then matches filters and takes priority on the other route.

You can exclude routes from a resourceful controller

Route::resource('parkings', 'Api\Parking\ParkingController')->except([
    'show',
]);
Route::get('parkings/filters', 'Api\Parking\ParkingFilterController');

The full documentation is here https://laravel.com/docs/7.x/controllers#restful-partial-resource-routes

If you wish a particular treatment with filters but still need the other route, you may add a global pattern to your router which will match everything against {parking} except filters.

https://laravel.com/docs/7.x/routing#parameters-global-constraints

Route::pattern('parking', '^(?!filters)([a-z0-9-_]+)$');
Related