Search code examples
phplaravelroutesurl-routinglaravel-api

Laravel API: url matching in api.php file


I am creating an API with Laravel 8 and in the requests to the different resources the path mapping does not behave as I would expect.

The entities are cameras and alert levels. A camera can have several alert levels.

The routes I have in the api.php file are:

//get the information of a specific camera. Works fine.
Route::get('cameras/{id}', [CameraController::class, 'getCamera']);

//get (all) alert levels information from all cameras
Route::get('cameras/alert-levels', [AlertLevelController::class, 'getCamerasAlertLevels']);

When I access this route:

http://www.example.com/api/v1/cameras/alert-levels

This route should match the second of the routes but however it is matching the first one.

If I alter the order of the routes they work correctly but I don't think I should have to do that. That is, it is supposed to detect that the URI does not match the first of the paths and that it does match the second.

Am I making a mistake?

Thank you very much in advance.


Solution

  • I bet, your id is numeric, so you can do the following using parameter constraints:

    //get the information of a specific camera. Works fine.
    Route::get('cameras/{id}', [CameraController::class, 'getCamera'])->where('id', '\d+'); // or ->whereNumber();
    
    //get (all) alert levels information from all cameras
    Route::get('cameras/alert-levels', [AlertLevelController::class, 'getCamerasAlertLevels'])