You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 5.4如何排除带参数的路由免受CSRF验证?

解决Laravel 5.4带参数路由的CSRF验证排除问题

Got it, let's sort out this CSRF exclusion issue for your parameterized routes in Laravel 5.4! The problem you're hitting is that you're using route parameter syntax ({id}) in the $except array, which doesn't work—instead, you need to use wildcards or regular expressions to match actual URL paths. Here are a few solid solutions:

方法一:使用通配符精确匹配子路由

Instead of writing main/{id}/sub/*, replace the parameter placeholder with a wildcard * (which matches any string). This will target exactly the routes under main/[any-value]/sub/ without excluding the entire main/* tree:

protected $except = [
    'main/*/sub/*',
];

This works because Laravel uses the Request::is() method under the hood to match entries in $except, and * acts as a catch-all for any segment in the URL path.

方法二:用正则表达式做严格匹配(比如ID仅为数字)

If you need tighter control—like ensuring the id segment is only a number—you can use a regular expression in the $except array. Just wrap your regex in delimiters (like # or /):

protected $except = [
    '#^main/\d+/sub/.*$#',
];

This regex will only match URLs where:

  • The path starts with main/
  • Followed by one or more digits (\d+) for the ID
  • Then /sub/
  • And ends with any additional path segments (.*)

方法三:重写shouldPassThrough方法(复杂场景)

For super custom exclusion logic (like checking request methods or specific parameter values), override the shouldPassThrough method in your App\Http\Middleware\VerifyCsrfToken class:

protected function shouldPassThrough($request)
{
    // Keep the original exclusion rules active
    if (parent::shouldPassThrough($request)) {
        return true;
    }

    // Add your custom matching logic here
    return preg_match('#^main/\d+/sub/.*$#', $request->path());
}

You can expand this further—for example, only exclude POST requests to those routes:

return $request->isMethod('post') && preg_match('#^main/\d+/sub/.*$#', $request->path());

小提示

Double-check that your excluded path matches the actual URL path your app uses. If you have a route prefix (like api/), don't forget to include it in the exclusion string/regex (e.g., api/main/*/sub/*).

内容的提问来源于stack exchange,提问作者blazR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:48:40