代码之家  ›  专栏  ›  技术社区  ›  vijaykumar

如何在中间件之前运行Laravel路由约束?

  •  1
  • vijaykumar  · 技术社区  · 6 年前

    我有这样的路线 /权限/{uuid} 我有路由约束和中间件。

    约束规则:将应用的所有路由的外接程序路由服务提供程序。

    Route::pattern('uuid', '[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}');
    

    public function handle($request, Closure $next)
    {
        $uuid = $request->route('uuid');
    
        // Check the uuid in DB and throw an exception
    
        return $next($request);
    }
    

    但这里的问题是中间件首先运行。如果uuid格式不正确,我只想避免db调用。我们可以先运行约束规则吗。

    编辑:

    1 回复  |  直到 6 年前
        1
  •  1
  •   Rwd    6 年前

    当Laravel收到一个请求时,它将首先通过全局中间件进行管道传输,然后尝试找到与该请求匹配的路由。如果它确实找到匹配的路由,那么它将运行您在路由文件、控制器构造函数等中为它指定的任何中间件,解析路由的任何方法参数,然后执行该方法。

    Route::pattern(...) 本质上为该参数添加了一个全局where子句。

    所以,如果你有 Route {uuid} 作为参数,只有在 uuid URI的一部分与提供给 Route::pattern


    例子:

    Route::pattern('uuid', '[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}');
    
    Route::get('test/{uuid}', 'SomeController@method');
    

    example.com/test/cfb81fde-9ce6-4a5e-8ddc-38417ef5425c
    

    这将导致404:

    example.com/test/1