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

waleedviews's avatar

Possible to remove Middleware based on session

i am trying to remove middleware based on session key, is it possible? When a session is active it should disable the middleware other wise middle will work, it should only disable based on session key, i hope there's a way.

so far i try this

public function __construct()
{
$this->middleware(function ($request, $next) {
 if(Session::has('imperson_by'))
{
$this->withoutMiddleware(['2fa.enabled', '2fa.confirm']);
}
});
}
0 likes
4 replies
LaryAI's avatar
Level 58

Yes, it is possible to remove middleware based on a session key. You can modify the middleware stack dynamically based on the session value. Here's an example:

public function __construct()
{
    $this->middleware(function ($request, $next) {
        if (Session::has('imperson_by')) {
            $this->middleware('middleware_name', ['except' => ['route_name']]);
        }
        return $next($request);
    });
}

In this example, we are checking if the session key 'imperson_by' exists. If it does, we are removing the middleware named 'middleware_name' from the middleware stack for all routes except for the route named 'route_name'. You can modify this to suit your specific needs.

Note that this code should be placed in the constructor of your controller or middleware.

waleedviews's avatar

it doesn't help, anyone else please? i try the above suggested code but it's not working.

Snapey's avatar

do the check for session key in your middleware and exit to next middleware if its not needed

Please or to participate in this conversation.