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

Ronster's avatar

Session In The Constructor

In the upgrade guide of Laravel 5.3 there is an example of how to get session data in a controller constructor.

$this->middleware(function ($request, $next) {
            $this->user = Auth::user();
            return $next($request);
        });

Apperantly the above doesn't so i'm looking for a way access the current user. the reason why is because I need to work with multiple schema's in progress and need to set those on the model.

thanks

0 likes
7 replies
Ronster's avatar

it always return null. although i am logged in.

InaniELHoussain's avatar

Taylor's word about it :

It’s very bad to use session or auth in your constructor as no request has happened yet and session and auth are INHERENTLY tied to an HTTP request. You should receive this request in an actual controller method which you can call multiple times with multiple different requests. By forcing your controller to resolve session or auth information in the constructor you are now forcing your entire controller to ignore the actual incoming request which can cause significant problems when testing, etc.

Ronster's avatar

if that's so. what is the best solution determine the account for a multi tenant app?

InaniELHoussain's avatar

Actually I cant help you more than that, the guys will do without doubt ;)

nate.a.johnson's avatar

There's not really enough info here to demonstrate your problem. I've built fully multi-tenant apps without ever needing to touch a constructor, so it is possible. It all depends on how you architect your application.

Ronster's avatar

We are handling sensitive data so we want to separate every account that is active. the idea is to have separate schema's, 1 per account. the public schema contains accounts and users. we don't have things like subdomains etc. all url's are the same.

I need account information as early as possible but have no idea what the best is to achieve that!.

Please or to participate in this conversation.