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

acupofcode's avatar

Session values getting nulled

Hey guys, I have a problem with session variables getting nulled on certain curcumstances. If a user logs into the clients single sign on solution he gets redirected to the Laravel application. With this initial request a special header will be sent. I need to retrieve the value from the header to be able to get user details from the database. I planned to retrieve the header in a Middleware (added to the web middleware group), get the details from the database and write the details into a session variable.

This approach works for the initial request, but after that, all requests will result in nulled session values.

<?php

namespace App\Http\Middleware;

use Closure;
use App\Models\UserDetail;

class CheckHeaders
{
    public function handle($request, Closure $next)
    {
        if ($request->headers->has('useridentifier')) {
            $userident = $request->header('useridentifier');
            $user = UserDetail::where('useridentifier', $userident)->first();
            session([
                'user' => [
                    'fn' => $user->firstname,
                    'ln' => $user->lastname,
                    'org' => $user->organisation,
                ]
            ]);
            return $next($request);
        }

        return abort(410);
    }
}

The result of the first request is:

'user' => [
                'fn' => 'jane',
                'ln' => 'doe',
                'org' => 'abc'
 ]

The result of every following request is always:

'user' => [
                'fn' => null,
                'ln' => null,
                'org' => null
]

What am I missing?

0 likes
3 replies
Snapey's avatar

are you logging the user into your Laravel application once you get the code? I ask because this will reinitialise the session.

1 like
m7vm7v's avatar

I would assume that when you have a the first request you hit the middleware with correct cred values and on the second you might recursively hitting it with some values that you do not want to trigger.

There might be a better solution and take this only as a workaround but have try with wrapping the session like so -

if($user){
    session([
                'user' => [
                    'fn' => $user->firstname,
                    'ln' => $user->lastname,
                    'org' => $user->organisation,
                ]
            ]);
}
acupofcode's avatar

@Snapey no, I don't use the laravel auth / login system

@m7vm7v tried this, but it still doesn't work. I suspect the $request->headers->has()to be the culprit. Even if it returns true/false correctly..

The header is only being sent with the initial request, so it shouldn't run into the whole "set session" thing..

Please or to participate in this conversation.