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

anonymouse703's avatar

What is the proper way to check user's session if exist in Middleware?

Hello everyone, I would like to check if the user's session exist then logout the user in middleware but i have this error.

error:array_key_exists(): The first argument should be either a string or an integer

public function handle($request, Closure $next) { $ip = $request->getClientIp(); $userAgent = $_SERVER['HTTP_USER_AGENT'];

    $userSession = session()->get([
        'user_id' => $request->user()->id,
        'ip_address' => $ip,
        'user_agent' => $userAgent
        ]);

    if ($userSession) {
        $this->auth->logout(); //this to logout specific user

        return redirect()->to(route('login'));
    }
    return $next($request);
}
0 likes
2 replies
bobbybouwmann's avatar

session()->get() only understands keys. You can't pass an array to it to check if the user exists. How did you create the session in the first place? You should have given that session a key. You can then retrieve the session using that key again.

Also you can use the has function here ;)

if (session()->has($key)) {
    $this->auth->logout(); //this to logout specific user

    return redirect()->to(route('login'));
}
anonymouse703's avatar

@bobbybouwmann I used session table... it automatically logged user who login in session table. I already solved the middleware i just make count.

by the way, do you have idea on how to destroy user's session when the user closed the browser?

Please or to participate in this conversation.