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

pascal83's avatar

Where to declare all my SESSION vars ?

Hello to all,

I have a question. In Laravel, where should i declare all my SESSION variables ?

In middleware ??

Thanks for your help !

Pascal

0 likes
4 replies
Snapey's avatar

Declare them when you use them. No point in doing it before.

Not sure why you need to use them in any great quantity though?

pascal83's avatar

Thanks Snapey for your message !

In the past, i made a website in PHP that use +- 20 session variables.. that keep user infos and some others informations

When a guest come to my site, i first initialize all session ex: $_SESSION["id"]="-1"

So often in my website, i check is $_SESSION["id"]==-1, and if yes... it means that the user is not logged...

So i wanted to do the same in Laravel but not just for user information...

Thanks a lot!

martinbean's avatar

@pascal83 Laravel has built-in user authentication. As @Snapey says, you should just be adding things to the session as and when you need to. Laravel has methods to check if a session value is defined or not, or to retrieve a default value:

// Will retrieve session value under “theme” key, or return “default” as default value
$theme = $request->session()->get('theme', 'default');
pascal83's avatar

Thanks Martinbean for the exemple.

I can get authenticated user info with Auth::id() if i want the id...

But, what is better... use session to get info of the user or use Auth:: ?

Because, when i do my test... every load page, when i use AUTH::.... it does a query to the DB ?

Is that normal ?

Thanks!

Please or to participate in this conversation.