skip to Main Content

I have a fresh installation of Laravel Sanctum API. When I try to log a user in after registration or when submitting the registration form twice, I get an exception with the message "The route dashboard could not be found". I don’t understand why it’s trying to redirect the user to the ‘dashboard’ route. The only place that I can see ‘dashboard’ in my project is in RouteServiceProvider.This seems like a bug too me with Sanctum.

enter image description here

3

Answers


  1. Make sure the dashboard route is added to the routes/web.php or routes/api.php file.

    ex: Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');
    
    Login or Signup to reply.
  2. this error shows when you try to register while you are already logged, so make sure to log out before register

    Login or Signup to reply.
  3. You are right, AppProvidersRouteServiceProviderRouteServiceProvider::HOME const is set to "/dashboard". If you follow the usage of this const you can see that is used by AppHttpMiddlewareRedirectIfAuthenticated middleware

    class RedirectIfAuthenticated {
    /**
     * Handle an incoming request.
     *
     * @param  Closure(IlluminateHttpRequest): (SymfonyComponentHttpFoundationResponse)  $next
     */
    public function handle(Request $request, Closure $next, string ...$guards): Response
    {
        $guards = empty($guards) ? [null] : $guards;
    
        foreach ($guards as $guard) {
            if (Auth::guard($guard)->check()) {
                return redirect(RouteServiceProvider::HOME);
            }
        }
    
        return $next($request);
    }
    }
    

    This middleware is aliased as "guest" in the AppHttpKernel:

    protected $middlewareAliases = [
        'auth' => AppHttpMiddlewareAuthenticate::class,
        'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
        'auth.session' => IlluminateSessionMiddlewareAuthenticateSession::class,
        'cache.headers' => IlluminateHttpMiddlewareSetCacheHeaders::class,
        'can' => IlluminateAuthMiddlewareAuthorize::class,
        'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
        'password.confirm' => IlluminateAuthMiddlewareRequirePassword::class,
        'signed' => AppHttpMiddlewareValidateSignature::class,
        'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
        'verified' => AppHttpMiddlewareEnsureEmailIsVerified::class,
    ];
    

    And this middleware is used in unauthenticated routes defined by routes/auth.php

    Route::post('/register', [RegisteredUserController::class, 'store'])
                ->middleware('guest')
                ->name('register');
    
    Route::post('/login', [AuthenticatedSessionController::class, 'store'])
                ->middleware('guest')
                ->name('login');
    
    Route::post('/forgot-password', [PasswordResetLinkController::class, 'store'])
                ->middleware('guest')
                ->name('password.email');
    
    Route::post('/reset-password', [NewPasswordController::class, 'store'])
                ->middleware('guest')
                ->name('password.store');
    

    This built-in middleware middleware will try and redirect you to the HOME if you are already authenticated.
    I think that there is an issue in Laravel breeze scaffolding (php artisan breeze:install api) that not provide a check on the response type in the
    AppHttpMiddlewareRedirectIfAuthenticated middleware.
    If you see instead the AppHttpMiddlewareAuthenticate middleware here is automatically provided a redirectTo method that check for the expected response ($request->expectsJson()):

    class Authenticate extends Middleware
    {
        /**
         * Get the path the user should be redirected to when they are not authenticated.
         */
        protected function redirectTo(Request $request): ?string
        {
            return $request->expectsJson() ? null : route('login');
        }
    }
    

    TLDR
    In short to work correctly with the AppHttpMiddlewareRedirectIfAuthenticated middleware in API based authentication you can add manually the following check in the middleware:

    foreach ($guards as $guard) {
    if (Auth::guard($guard)->check()) {
      if ($request->expectsJson()) {
        return response()->json(['error' => 'Already authenticated.'], 200);
      }
      return redirect(RouteServiceProvider::HOME);
    }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search