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

Laravel中auth中间件跳转登录页缺失lang参数问题求助

问题解决思路

核心原因

Laravel自带的auth中间件在跳转登录页时,不会自动携带你的多语言路由参数{lang},而你的登录路由是带语言前缀的,所以导致参数缺失报错。

具体解决步骤


1. 自定义Auth中间件

创建自定义中间件替换默认的auth中间件,让跳转登录页时自动带上语言参数:
首先生成中间件:

php artisan make:middleware LocalizedAuth

打开app/Http/Middleware/LocalizedAuth.php,修改内容:

<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;

class LocalizedAuth extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            // 携带当前语言参数跳转登录页
            return route('login', app()->getLocale());
        }
    }
}

2. 替换默认Auth中间件

打开app/Http/Kernel.php,找到$routeMiddleware数组,替换默认的auth中间件:

protected $routeMiddleware = [
    // ...
    // 注释原默认条目
    // 'auth' => \App\Http\Middleware\Authenticate::class,
    'auth' => \App\Http\Middleware\LocalizedAuth::class,
    // ...
];

3. 确认登录路由的前缀配置

确保你的登录路由是包裹在语言前缀组内的,比如routes/web.php里的配置:

Route::prefix('{lang}')->group(function () {
    Auth::routes();
    // 其他带语言前缀的路由...
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 09:51:55