Session
What is Session?

Session is use to store information in variable and this session variable is available in whole project, Means we can
access session variable in any of the webpage in project.

For Maintain Session Laravel provides us various drivers like file, cookie, apc, array, memcached, redis and database
But by default laravel use file driver because this is lightweight

To configure session driver we go to

config/session.php
.env

How to Store session data?

Route
Route::get('/entry1', 'HomeController@entry1');

Controller
Create entry1 function in controller
public function entry1(Request $request)
{
$request->session()->put('username', 'shishirphpdeveloper');
}

where username is a session key and shishirphpdeveloper is session key value

How to Access session data?

Route
Route::get('/entry2', 'HomeController@entry2');

Controller
Create entry2 function in controller
public function entry2()
{
echo session()->get('username','Default');
}

This echo statement print session value if username session key does not exist then this will print
Default

How to Delete session data?

Route
Route::get('/entry3', 'HomeController@entry3');

Controller
Create entry3 function in controller
public function entry3()
{
$request->session()->forget('username');
}

This statement is use to delete username session key

Other Laravel session function

Flush
$request->session()->flush();
To delete all session data

Pull
$request->session()->pull('key', 'default');
To retrieve delete data from session and delete it afterwards

FlashData
$request->session()->flash('status', 'Task was successful!');
To Flash Data for message

Retrieving All Session Data
$request->session()->all();

Reflash and Keep
Reflash function to keep all of the flashdata and keep is use for specific data
$request->session()->reflash();
$request->session()->keep(['username', 'email']);


Previous
Next