kendrick's avatar

How to redirect a !auth-user to a specific route (middleware)?

How can I redirect a not-authenticated user to the log-in view when one clicks on a protected route? E.g. our homepage is protected therefore we should directly redirect a user to the log-in route.

web.php

homepage -> middleware('auth');
e.g. legal -> (no middleware);
login -> middleware('guest'); // destination to be redirected to, if clicked on auth protected route, as !logged-in user

Is there a difference between production and local development, because currently I am seeing one.

Locally it redirects to the log-in route, always, whereas in production it redirects to a 500 error view, instead.

Where is the default logic to handle the case. In our Handler.php or Authenticate.php (middleware) file?


// something like: return redirect()->guest('/login'); // if we visit a auth protected route
0 likes
3 replies
rodrigo.pedra's avatar
Level 56

The logic to handle authentication redirection is located in the Authenticate middleware, located in your project's app/Http/Middleware.

You should change line 18 in this file:

https://github.com/laravel/laravel/blob/master/app/Http/Middleware/Authenticate.php#L18

To return an URL to the desired route where to redirect a guest user. By the default it redirects to a named route with name login. If you are not using the default auth scaffolding you can manually change this file for something you are using, for example:

        if (! $request->expectsJson()) {
            return url('/login');
        }
Tray2's avatar

If you are using the Auth provided in the laraval ui it's default behaviour.

In laravel < 6 you just run php artisan make:auth but from version 6 you need to install the laravel ui

https://laravel.com/docs/6.x/releases

kendrick's avatar

Thank you, was missing this line.

1 like

Please or to participate in this conversation.