Skip to content
Advertisement

How can I define a route differently if parameter is not integer

I am using Laravel 5 and working on my local. I made a route with a parameter of {id} and another route with a specific name like so :

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

My problem here is that if I try to go at localhost/contacts/new it will automatically access to the get_contact method. I understand that I have made a {id} parameter but what if I want to call get_contact only if my parameter is an integer? If it is not, check if it’s “new” and access to new_contact method. Then, if it’s not an integer and not “new”, error page 404.

How can I do that in Laravel 5?

Thanks for your help!

Advertisement

Answer

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

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

Read more: http://laravel.com/docs/master/routing#route-parameters

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement