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

Laravel如何判断category路由仅含一级子路径(无后续层级)

Fixing the Active Nav Class for Single-Level Category URLs

Got it, let's sort out that incorrect URL matching for your navigation active class! The problem with Request::is('category/*') is that the * wildcard matches any character including slashes, so it's catching multi-level paths like category/goodwin/new when you only want to target single-level ones like category/goodwin.

Here are two clean solutions to fix this:

Solution 1: Use Laravel's Segment Count (Native & Readable)

Laravel's Request facade has a segmentCount() method that tells you how many path segments exist. For a single-level category URL (category/[slug]), the segment count will be 2 (since segments start at 1: segment(1) is "category", segment(2) is your slug).

Update your condition to combine Request::is('category/*') with a check for exactly 2 segments:

{{ Request::is('popular') || Request::is('/') || Request::is('category/*/popular') || (Request::is('category/*') && Request::segmentCount() === 2) ? 'nav-active' : '' }}

This ensures we only match category/[slug] and exclude any paths with extra slashes after the category slug.

Solution 2: Regular Expression Match (Flexible)

If you prefer a regex-based approach, you can use Request::path() to get the full path (without domain) and match it against a regex that enforces a single level after category/:

{{ Request::is('popular') || Request::is('/') || Request::is('category/*/popular') || preg_match('/^category\/[^\/]+$/', Request::path()) ? 'nav-active' : '' }}

The regex ^category\/[^\/]+$ means:

  • ^: Start of the string
  • category\/: Exact match for "category/"
  • [^\/]+: One or more characters that are NOT a slash
  • $: End of the string

This strictly limits the match to single-level category URLs.

Both solutions will preserve your working logic for popular, the root path, and category/*/popular while fixing the over-matching issue. Pick whichever fits your coding style better!

内容的提问来源于stack exchange,提问作者mile-panic

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:10:33