资源路由的正则表达式路由约束 [英] Regular expression route constraint for a resource route
问题描述
Laravel提供了向这样的路由添加正则表达式约束的可能性:
Laravel offers the possibility to add regular expression constraint to a route like this:
Route::get('user/{name}', function($name)
{
//
})
->where('name', '[A-Za-z]+');
还可以为一个资源创建多个路由:
it is also possible to create multiple routes for a resource:
Route::resource('photo', 'PhotoController');
我只想将正则表达式约束添加到路由GET /photo/{id}
I want to add regular expression constraint only to the route GET /photo/{id}
有可能吗?
推荐答案
据我所知您无法做到,但您可以使用以下类似方法(路由过滤)来模仿:
As far as I know you can't but you may mimic that using something like this (route filtering):
public function __construct()
{
$this->beforeFilter('checkParam', array('only' => array('getEdit', 'postUpdate')));
}
这是使用构造函数进行路由过滤的示例,在这里,我仅过滤两种方法(您可以使用except
或根本不使用任何方法),并在filters.php
文件中声明过滤器,如下所示:
This is an example of route filtering using the constructor and here I've filtering only two methods (you may use except
or nothing at all) and declared the filter in filters.php
file as given below:
Route::filter('checkParam', function($route, $request){
// one is the default name for the first parameter
$param1 = $route->parameter('one');
if(!preg_match('/\d/', $param1)) {
App::abort(404);
// Or this one
throw new Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
}
});
在这里,我正在手动检查第一个参数(parameters
方法返回传递给路由的所有参数的数组),如果不是数字,则抛出NotFoundHttpException
异常.
Here, I'm checking the first parameter manually (parameters
method returns an array of all parameters passed to the route) and if it's not a digit then throwing NotFoundHttpException
exception.
您还可以通过注册如下处理程序来捕获异常:
You may also catch the exception by registering a handler like this:
App::missing(function($exception){
// show a user friendly message or whatever...
});
这篇关于资源路由的正则表达式路由约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!