问题描述
我正在使用Laravel 5并在本地工作.我制作了一条带有{id}参数的路由,以及另一条具有特定名称的路由,如下所示:
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');
我的问题是,如果我尝试访问localhost/contacts/new,它将自动访问get_contact方法.我知道我已经创建了一个{id}参数,但是如果仅当我的参数是整数时才想调用get_contact怎么办?如果不是,请检查它是否为"new"并访问new_contact方法.然后,如果它不是整数而不是"new",则显示错误页面404.
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.
我如何在Laravel 5中做到这一点?
How can I do that in Laravel 5?
感谢您的帮助!
推荐答案
只需将->where('id', '[0-9]+')
添加到要接受仅数字参数的路由即可:
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');
了解更多: http://laravel.com/docs/master/routing#route -参数
这篇关于如果参数不是整数,我该如何不同地定义路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!