Laravel如何判断category路由仅含一级子路径(无后续层级)
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 stringcategory\/: 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

