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

stefanbauer's avatar

Session ID is different in constructor and action

Hi,

it's a really strange thing. If i output session()->getId() on my /cart page in my CartController in the __construct, it changes on every request. Additionally i output it on the index-method, it stays the same (as it should). Any ideas why this happens?

Here is the example code snippet that's relevant:

class CartController
{
    public function __construct()
    {
        \Debugbar::info('session()->getId() in CartController::construct '.session()->getId());
    }


    public function index()
    {
        \Debugbar::info('session()->getId() in CartController::index '.session()->getId());

        return 'index';
    }
}

Here is the result for 3 request:

Request 1

session()->getId() in CartController::construct XyFBsUvi9GTrl7JKVJmVbuumaVP7BHV09iIj1X7L
session()->getId() in CartController::index cBdeAHMCKLWZmfS3Vb1Ji2ZPpqeJctj5IAqRYuaV

Request 2

session()->getId() in CartController::construct WyK1QzcCfEd88wVYYYf61D79UyE1h9Xj6cMDkCKl
session()->getId() in CartController::index cBdeAHMCKLWZmfS3Vb1Ji2ZPpqeJctj5IAqRYuaV

Request 3

session()->getId() in CartController::construct 1rXdH7K88VJMtslHl7d1ZVlTgHH8ajeZjbMyxztj
session()->getId() in CartController::index cBdeAHMCKLWZmfS3Vb1Ji2ZPpqeJctj5IAqRYuaV

As you can see, the one in the index method is always the same. And in the constructor it changes on each request. Am i missing something? Don't get it why this happens.

PS: Laravel 5.5

0 likes
3 replies
deansatch's avatar

I don't think you are supposed to mess with your sessions inside a constructor in general so to fix the problem, just don't do it.

That said, I expect the reason it is different is because laravel will run the constructor before it runs middleware and I think session start is in middleware.

1 like
stefanbauer's avatar

In any case, thanks! Got it.

The thing was that i inject a repository there in the constructor. And this repository uses the session id as the "id" for its identification in a specific database table. There is a findCurrent() method, that has a firstOrCreate($sessionId) method on it (this session id changes on every request, because i inject this service in the constructor). This worked in L5.4.

That in mind means, i don't use the sessionId directly in the constructor. Just a service uses it, which is injected there. I am not sure if the the "solution" is then just not to use the session id in the constructor or in any dependent service that is injected somewhere (because that's the idea of the container). So not sure if my approach is a really wrong one (but understand now, why this happens).

Please or to participate in this conversation.