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

Laravel 5.5本地化前缀与中间件部分路由失效问题排查

Troubleshooting Laravel 5.5 Locale Middleware for Multi-Level Routes

Hey Jimmy, let's break down why your /search/categories route isn't triggering the locale middleware while /home works—this is usually a routing structure or matching priority issue, so let's walk through the fixes step by step.

1. Check Your Route Group Structure & Order

The most common culprit here is that your multi-level routes aren't properly nested inside the locale-prefixed group, or you've defined a conflicting route outside the group that's being matched first.

Correct Group Setup

Make sure all routes that need the locale prefix are wrapped in the same group with both the {lang?} prefix and your locale middleware. Laravel matches routes in the order they're defined, so if you have a standalone /search/categories route defined before the locale group, it'll be hit first and skip the middleware entirely.

// Put this at the top of your routes/web.php (before any standalone routes)
Route::group(['prefix' => '{lang?}', 'middleware' => 'locale'], function () {
    // Works correctly
    Route::get('/home', 'HomeController@index');
    // This should now trigger the middleware too
    Route::get('/search/categories', 'SearchController@categories');
    
    // Add all other locale-dependent routes here
});

2. Fix Middleware Logic for Multi-Level Paths

If your middleware isn't correctly handling paths with multiple segments (like /search/categories), it might fail to redirect properly. Double-check how you're extracting the non-locale path from the request.

Example of a Robust Locale Middleware

Here's an adjusted version that handles empty paths and multi-segment URLs without breaking:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\App;

class Locale
{
    public function handle($request, Closure $next)
    {
        $locale = $request->route('lang');
        $allowedLocales = config('app.locales', ['en', 'zh']);
        
        // If no valid locale is present, redirect with default
        if (!in_array($locale, $allowedLocales)) {
            $defaultLocale = config('app.locale', 'en');
            // Trim leading/trailing slashes to avoid double slashes in URLs
            $requestPath = trim($request->path(), '/');
            
            // Build the redirect URL—handle empty root path case
            $redirectUrl = empty($requestPath) 
                ? "/{$defaultLocale}" 
                : "/{$defaultLocale}/{$requestPath}";
            
            return redirect()->to($redirectUrl);
        }
        
        // Set the app locale
        App::setLocale($locale);
        return $next($request);
    }
}

3. Clear Route Cache

Laravel 5.5 caches routes when you run php artisan route:cache, which can freeze outdated route structures. If you've recently adjusted your route groups, clear the cache to make sure Laravel picks up the changes:

php artisan route:clear

4. Verify Route List

Run the route list command to confirm your /search/categories route is correctly associated with the locale prefix and middleware:

php artisan route:list

Look for a route with URI {lang?}/search/categories and middleware including locale. If it shows up as just /search/categories without the prefix, that means it's not in the right group.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:46:58