Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 246
Matthieu Boisjoli Avatar asked May 23 '15 16:05

Matthieu Boisjoli


People also ask

What is a route parameter?

Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the req.params object, with the name of the route parameter specified in the path as their respective keys.

What is Route parameter in laravel?

Laravel routes are located in the app/Http/routes. php file. A route usually has the URL path, and a handler function callback, which is usually a function written in a certain controller.


1 Answers

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

like image 200
Limon Monte Avatar answered Sep 22 '22 19:09

Limon Monte