Http Session tutorial in laravel 8

Session :We can set the session data with two ways.

i. Golbal Session helper : global[‘key’=>’value’]

ii. Via Request Instance : $request->session()->put(‘key’,’value’)

Also we can get the session data using two ways

Global session: session(‘key’)

Retrieve all session data:





then,we check to see if an item exits:

In route setting some key for session using global session helper.

session(['key' => 'value']);


When we use has method with session() it will return true if user present in session .

if ($request->session()->has('user'))
    return $request-session()->get(‘user’);
else if ($request->session()->has('key'))
     return $request->session()->get('key');


Result will be “value” as it will not return anything if a key’s value is null.We can also do this with exist method

    return "User :".$request->session()->get('users');
else if($request->session()->exists('key'))
    return "Key :".$request->session()->get('key');


But this time the result will come from ‘users’ key as it will return the value even if the key is null value.

Missing Method:

Using missing with session we can determine if a key is missing

if ($request->session()->missing('kkk'))
    return 'missing';

Setting and getting new value to session array using put

return $request->session()->pull('key2');



 if ($request->session()->has('key2'))
    return 'user';
     return 'missing key2';


The result will be ‘missing key2’ as  pull not only retrieve the key but also delete the key.

Incrementing and decrementing:

We can increment and decrement the session value

echo  $request->session()->increment('key5');

 return $request->session()->increment('key5');



Result will 1 for first statement , 2 for second statement and 1 for last statement.

Note; When we use increment, decrement, it will automatically set the session value for us.

Flash Data:If we want to set the for next request then have to save the data using flash.



Deleting Session data:


To remove all data  we have to use flash()



Session Fixation : When an attacker  hijack a valid user session is called Session Fixation.

Regenerating The session ID:

To prevent session fixation we have to regenerate session id . Laravel automatically regenerates the session ID during authentication we we use one of the Laravel application starter kits or Laravel Fortify. Otherwise we have to do it manually



We also can regenerate() the session and remove all session data with it using below code




Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top