How to use Session in Laravel

Hello artisans, today I’ll talk about how to use session in our Laravel Application. A session variable used to store some information which we can retrieve anywhere in our application. So, let’s see how we can use it in our application.

Note: Tested on Laravel 8.67.

Table of Contents

  1. Store Data into session
  2. Retrieve Data from session
  3. Regenerating ID’s
  4. Deleting Session Values

Store Data into session

Laravel provides a helper methods called session().We can easily store value easily by put() method

session()->put('key','value');

you can also push a value into an array session by push() method

session()->push('key','value');

Retrieve Data from session

Retrieving a value from the session is also easy like store like below you can retrieve the specific value a session

session()->get('key');

You can also retrieve all the session values by using the all() method.

session()->all();

You can also check if an item exists in the session and then you can fetch that, for that you have to use has() method.

if (session()->has('key')) {
    // perform your logics here
}

Regenerating ID’s

If you want to regenerate all the IDs for the session, you can use the regenerate() method.

session()->regenerate();

Deleting Session Values

You can use forget() method forget a specific key from a session.

session()->forget('key');

You can also delete all the session items, for that you have to use flush() method.

session()->flush();

That’s all for today. Thanks for reading. ?