How to define a route differently if the parameter is not integer

I am using Laravel 5 and working on my local one. I made a route with the {id} parameter and another route with the same name:

Route::get('contacts/{id}', ' ContactController@get _contact'); Route::get('contacts/new', ' ContactController@new _contact'); 

My problem is that if I try to switch to localhost / contacts / new, it will automatically get access to the get_contact method. I understand that I made the {id} parameter, but what if I want to call get_contact only if my parameter is an integer? If this is not the case, check if it is "new" and access the new_contact method. Then, if it is not an integer, and not a "new", page 404 error.

How can I do this in Laravel 5?

Thank you for your help!

+5
source share
2 answers

Just add ->where('id', '[0-9]+') for routing, where you want to accept the parameter for number only:

 Route::get('contacts/{id}', ' ContactController@get _contact')->where('id', '[0-9]+'); Route::get('contacts/new', ' ContactController@new _contact'); 

More details: http://laravel.com/docs/master/routing#route-parameters

+11
source

There is also the option to simply switch between them, because the route file will go through all the lines from top to bottom until it finds the correct route.

 Route::get('contacts/new', ' ContactController@new _contact'); Route::get('contacts/{id}', ' ContactController@get _contact'); 

If you want to limit this route to pure numbers, the marked solution is correct though.

Just adding it here, I know it's pretty old;)

+1
source

All Articles