由Auth中间件引起的Laravel 8路由未定义错误



我正试图访问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导致以下错误:

SymfonyComponentRoutingExceptionRouteNotFoundException
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内外发现了许多类似的帖子,但这些解决方案都没有帮助。

我的默认路线命名错误了吗?我可以不在我的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');
}
}
}

最新更新