Search code examples
laravelauthenticationlaravel-5.3laravel-middleware

Redirect if authenticated in Laravel 5.3


I'm using the Auth scaffold in Laravel 5.3 and I've changed the routes for the auth. So instead of /login and /register I use /signin and /signup.

In Laravel 5.2 we had this by default in the auth middleware,

public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->guest()) {
        if ($request->ajax() || $request->wantsJson()) {
            return response('Unauthorized.', 401);
        }

        return redirect()->guest('login');
    }

    return $next($request);
}

This would redirect to the login route if the user wasn't logged in. In Laravel 5.3 we have this,

public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->check()) {
        return redirect('/');
    }

    return $next($request);
}

This redirects an already logged in user to the default route /. So they switched it around in 5.3. Instead of defining where guest go, we define were logged in users go.

My question is, how would I natively to Laravel 5.3 change were guests go?

Because at the moment, people who try to access sites protected by the middleware automatically end up at a /login route. I would like to change this to /signin but I can't find anywhere to customize this behaviour.

Any ideas?


Solution

  • how would I "natively" to Laravel 5.3 change were guests go?

    Looks like there's a new unauthenticated() method in app/Exceptions/Handler.php which handles unauthenticated users and redirects to login.

    As this is part of your app, no reason you couldn't customize it to redirect elsewhere.