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

Laravel 11自定义Authenticate中间件报错Route [login]未定义的解决

Laravel 11 自定义认证中间件「Route [login] not defined」错误排查与解决

问题背景

Laravel 11移除了默认的Authenticate中间件,自行创建认证中间件后,未认证用户访问受保护路由时触发「Route [login] not defined」错误。

错误原因

  1. 中间件引用错误:路由中使用的是框架原生的Illuminate\Auth\Middleware\Authenticate类,而非你自定义的App\Http\Middleware\Authenthicate类(注意类名拼写多了一个h)。
  2. 原生中间件默认逻辑:框架原生的Authenticate中间件会默认尝试跳转名为login的路由,但你的登录路由名称是admin.auth.index,未定义login路由,因此报错。

解决步骤

1. 修正中间件类名(可选但建议)

将自定义中间件的类名从Authenthicate修正为标准的Authenticate,避免后续混淆:

<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;

class Authenticate 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('admin.auth.index');
        }
    }
}

2. 路由中引用自定义中间件

修改web.php,替换框架原生中间件为自定义中间件:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Admin\AuthController;
// 替换为自定义中间件
use App\Http\Middleware\Authenticate;

Route::get('/', function () {
    return view('welcome');
});

Route::group(['prefix' => 'admin'], function (){
    Route::view('/login', 'login')->name('admin.auth.index');
    Route::post('login', [AuthController::class, 'login'])->name('admin.auth.login');
});

// 使用自定义中间件保护路由组
Route::middleware([Authenticate::class])->group(function () {
    Route::view('/', 'dashboard')->name('admin.dashboard');
});

3. 注册自定义中间件(Laravel 11 必需)

在bootstrap/app.php中注册自定义中间件,可设置别名简化使用:

// bootstrap/app.php
return Application::configure(basePath: dirname(__DIR__))
    // ...其他配置项
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->alias([
            'auth' => \App\Http\Middleware\Authenticate::class,
        ]);
    })
    ->create();

注册别名后,路由中可直接使用auth替代完整类名:

Route::middleware(['auth'])->group(function () {
    Route::view('/', 'dashboard')->name('admin.dashboard');
});

内容的提问来源于stack exchange,提问作者Dimas Seto Rizky Goenardi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 14:47:26