0

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.

2 Answers 2

1

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'])
Sign up to request clarification or add additional context in comments.

Comments

0

You should change order of routes.Because both get request and it matches first one so it goes to cameras/{id}.

so dynamic param string then we must kept last.or else you can follow other answer mentioned by @shaedrich.

for security reason usually id passed as encrypted so it will generate long string

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

Route::get('cameras/{id}', [CameraController::class, 'getCamera']);

2 Comments

Good point about encryption. Often times, UUID or GUID is used instead of auto increment integer. Regexes can be defined for that cases as well.
@shaedrich.ya but i am not good at regex so.:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.