Moh*_*gue 6 regex laravel laravel-4
Laravel提供了向这样的路由添加正则表达式约束的可能性:
Route::get('user/{name}', function($name)
{
//
})
->where('name', '[A-Za-z]+');
Run Code Online (Sandbox Code Playgroud)
也可以为资源创建多个路由:
Route::resource('photo', 'PhotoController');
Run Code Online (Sandbox Code Playgroud)
我想只为路由添加正则表达式约束 GET /photo/{id}
那可能吗?
在Laravel 5中,资源丰富的路由参数可以这样命名:
Route::resource('user', 'UserController', ['parameters' => [
'user' => 'id'
]]);
Run Code Online (Sandbox Code Playgroud)
这可以与路线模式结合使用:
Route::pattern('id', '[0-9]+');
Run Code Online (Sandbox Code Playgroud)
因此,您可以轻松地为路由参数定义单个全局约束,并对所有资源丰富的路由使用if.
据我所知你不能,但你可以使用类似的东西(路由过滤)来模仿:
public function __construct()
{
$this->beforeFilter('checkParam', array('only' => array('getEdit', 'postUpdate')));
}
Run Code Online (Sandbox Code Playgroud)
这是使用构造函数进行路由过滤的示例,在这里我仅过滤了两种方法(您可以使用except或根本不使用)并在filters.php文件中声明过滤器,如下所示:
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;
}
});
Run Code Online (Sandbox Code Playgroud)
在这里,我手动检查第一个参数(parameters方法返回传递给路由的所有参数的数组),如果它不是数字,则抛出NotFoundHttpException异常。
您还可以通过注册如下处理程序来捕获异常:
App::missing(function($exception){
// show a user friendly message or whatever...
});
Run Code Online (Sandbox Code Playgroud)