php - 如果参数不是整数,如何以不同方式定义路由

标签 php laravel routes

我正在使用 Laravel 5 并在本地工作。 我创建了一个参数为 {id} 的路由和另一个具有特定名称的路由,如下所示:

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

我的问题是,如果我尝试访问 localhost/contacts/new,它将自动访问 get_contact 方法。我知道我已经制作了一个 {id} 参数,但是如果我只想在我的参数是整数时调用 get_contact 怎么办?如果不是,请检查它是否是“新的”并访问 new_contact 方法。然后,如果它不是整数且不是"new",则错误页面 404。

我如何在 Laravel 5 中做到这一点?

感谢您的帮助!

最佳答案

只需添加 ->where('id', '[0-9]+') 到您想要接受纯数字参数的路由:

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-parameters

关于php - 如果参数不是整数,如何以不同方式定义路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30414860/

相关文章:

php - 如何在 MySQL 中使用 INET_ATON 对 IP 地址进行通配符搜索?

php - 按字母顺序对 MYSQL 结果进行升序排序,但不将 'The' 排序为 T?

c# - PHP 到 C#.NET/ASP.NET

php - Laravel + MySQL - 存储 Eloquent 命名空间

android - Google Maps API 版本差异

javascript - 打开时尝试将数据从数据库传递到引导模式。我该怎么做呢?

php - 在 Laravel 中使用节点模块

php - 如何使用 `where` 子句在 Laravel 5 中执行连接?

angular - 路由器在 async/await 方法中导航立即执行

node.js - 如何在 Express 路由中设置 Next.js 渲染?