Laravel 8 Auth Middleware 导致的 Route not Defined 错误

Laravel 8 Route not Defined Error Caused by Auth Middleware

我正在尝试访问我的 routes/web.php 文件中定义的路由:

Route::get('/dashboard', [ConsoleController::class, 'dashboard'])->middleware('auth');

我没有登录。Authenticate.php 中间件文件试图将我重定向回登录页面:

class Authenticate extends Middleware
{
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            return route('');
        }
    }
}

我也试过在 Authenticate.php 中间件中使用 return route('/');

我的 routes/web.php 文件有一个默认路由,如果我手动转到该页面,它可以正常工作:

Route::get('/', [ConsoleController::class, 'loginForm'])->middleware('guest');

但是,Authenticate.php 导致了以下错误:

Symfony\Component\Routing\Exception\RouteNotFoundException
Route [] not defined.
http://localhost:8888/dashboard

它指向以下代码行:

public function route($name, $parameters = [], $absolute = true)
{
    if (! is_null($route = $this->routes->getByName($name))) {
        return $this->toRoute($route, $parameters, $absolute);
    }
    throw new RouteNotFoundException("Route [{$name}] not defined.");
}

我在 Stack Overflow 上和其他地方发现了许多类似的帖子,但是 none 这些解决方案有所帮助。

我的默认路由命名有误吗?我不能在我的 Authenticate.php 中间件中使用这条路由吗?任何帮助将不胜感激。

问题是,您正在使用 Laravel 的 route() 方法,它希望将路由名称作为参数,但您传递的是实际 url.

在您的 routes/web.php 文件中,将名称添加到您的路线中

Route::get('/dashboard', [ConsoleController::class, 'dashboard'])->middleware('auth')->name('dashboard');

然后在你的 Authenticate 中间件文件中,

class Authenticate extends Middleware
{
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            return route('dashboard');
        }
    }
}