PHP Laravel: How to set or get Session Data?
You haven't made a coding mistake. The issue is that you're getting a little confused between server side sessions and HTML5's sessionStorage.
The Resources->Session Storage
view on the Chrome Developer Tools is only showing you the information stored in the HTML5 sessionStorage object. This is client side session information that is accessed via client side javascript, and is completely separate from any type of server side session information.
For example, run sessionStorage.setItem('key', 'value');
in your javascript console, and you will see that data show up in the Resources->Session Storage
view.
Your PHP/Laravel code is dealing with server side sessions. This information is not going to show up in any type of Developer Tools view because it is not meant to be accessed by client side tools. By default, Laravel uses file based session storage, which means your session information is stored in files on your server (in storage/framework/sessions
). Even if you change the session storage to use cookies, the session information will be encrypted so that the client side cannot read the data. This is for security purposes.
You can read more about Laravel sessions here.
You can read more about HTML5 sessionStorage here.
Storing data
To store data, you can use:
Session::put('variableName', $value);
There is also another way, through the global helper:
session(['variableName' => $value]);
Getting data
To get the variable, you'd use:
Session::get('variableName');
if you have existing value on that session variable, first you need to clear it. then you can replace new value like this.
session()->forget('key');
session()->put('key', 'value');