Is it because a model doesn't depend on any session ? That would be logical.
Oct 16, 2022
9
Level 63
Retrieve session data from model
Hello,
I tried to retrieve a session data from the model.
public function getCurrentCompanyId()
{
return session('company_id');
}
But it always returns null.
Whereas if I retieve the session data from a trait or any scope, it returns the right value stored in the session.
Why ?
Can you help me to understand ?
Thanks.
Vincent
Level 104
@vincent15000 you could do this in a custom Middleware - it could be as simple as
public function handle($request, $next)
{
if (auth()->check()) {
auth()->user()->current_company_id = $request->session('company_id');
}
return $next($request);
}
You could initialize a public property on the User model for completeness:
public ?int $current_company_id = null;
Now, you can make this custom middleware global, or a route middleware; up to you. Just ensure it is handled after the Session is started and the User is authenticated
1 like
Please or to participate in this conversation.