Home > front end >  Laravel 8 Route not Defined Error Caused by Auth Middleware
Laravel 8 Route not Defined Error Caused by Auth Middleware

Time:02-06

I am attempting to access a route defined in my routes/web.php file:

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

I am not logged in. The Authenticate.php middleware file attempts to redirect me back to the login page:

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

I have also tried using return route('/'); in the Authenticate.php middleware.

My routes/web.php file has a default route which works fine if I go to the page manually:

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

However, the Authenticate.php is causing the following error:

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

And it points to the following line of code:

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.");
}

I have found many similar posts on and off Stack Overflow, but none of those solutions have helped.

Am I naming my default route wrong? Can I not use this route in my Authenticate.php middleware? Any help would be appreciated.

CodePudding user response:

Issue is, you are using route() method of Laravel, which expect route name as a parameter but you are passing actual url.

In your routes/web.php file, add name to your route as

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

Then in your Authenticate middleware file,

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