Laravel 11自定义Authenticate中间件报错Route [login]未定义的解决
Laravel 11 自定义认证中间件「Route [login] not defined」错误排查与解决
问题背景
Laravel 11移除了默认的Authenticate中间件,自行创建认证中间件后,未认证用户访问受保护路由时触发「Route [login] not defined」错误。
错误原因
- 中间件引用错误:路由中使用的是框架原生的
Illuminate\Auth\Middleware\Authenticate类,而非你自定义的App\Http\Middleware\Authenthicate类(注意类名拼写多了一个h)。 - 原生中间件默认逻辑:框架原生的
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
相关产品推荐
相关产品推荐

