Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rearmustak's avatar

Redirect to custom login page by auth middleware

Without generating Laravel default auth controllers, I create my own login and registration controller.

My routes look like these For Login

GET   /login   ->> SessionController@create -->name = login.create
POST  /login   ->> SessionController@store -->name = login.store

For Registration

GET     /registration   ->> RegistrationController@create  -->name = register.create
POST    /registration   ->> RegistrationController@store   -->name = register.store

Everything is fine. Now I need one thing. Whenever I put auth middleware, a non-authenticated user will be redirected to my custom login page route to login.create.

How to do this?

0 likes
2 replies
rearmustak's avatar
rearmustak
OP
Best Answer
Level 5

I got my solution.

Here is the solution

You can extend Illuminate\Auth\Middleware\Authenticate middleware or just add a new middleware:

class AuthMiddleware
{
    public function handle($request, Closure $next)
    {
        if (auth()->guest()) {
            return redirect()->route('login.create');
        }

        return $next($request);
    }
}

Register it in App\Http\Kernel.php:

protected $routeMiddleware = [
    'auth.custom' => \App\Http\Middleware\AuthMiddleware::class,
    ....
3 likes
Snapey's avatar

If you want to use the built in auth middleware, all you need to do is create a route named login

when you use auth middleware and the user is not logged in then an exception is thrown. This is caught in the ExceptionsHandler and in the case of Unauthenticated, the route named login is called or a json response is returned if applicable

1 like

Please or to participate in this conversation.