How to use Session in Laravel

In a login and registration process, we have to identify the user in the whole project once the user gets authenticated. We all know that we use sessions to store information about the user across the request. So in this post, we will learn about the Laravel session and its use.

Laravel has various drivers like file, cookie, Memcached, array, apc, Redis, and database to handle session data.

By default, the file driver is used because of its lightweight. We can change it to any other driver if we want.

You can configure session files at config/session.php

How to Store Session Data

We can store the data in session using put() method. It takes two arguments the key and the value.

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

How to Access Session Data

We can access the session data using get() method. In it, we get the value of session using the keyName stored in the session.

$value = $request->session()->get('key');

How to Delete Session Data

We can delete the session data using forget() method. We only need to pass the key as an argument in the forget() method to delete that particular session data.

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

How to delete all Session data at once

If you would like to remove all data from the session, you may use the flush() method:

$request->session()->flush();

Use of pull() method

Use the pull() method to retrieve data from session and delete it afterward.

The main difference between the forget() and the pull() method is that forget() method delete the value from the session and pull() method will return it and delete that value from session.

$request->session()->pull('key', 'default');

How to get Session value in view

    @if(session::has('key'))
        {{ session::get('key') }}
    @endif
  

Check if an item exists in Session

Using the has method you can check if the value is present in the session or not. If value present in the session it will return true otherwise false.

 if($request->session()->has('key'))
 {
// 
 }

Conclusion:

Sessions are very useful in any web programming. Laravel provides very easy to use methods to access modify and delete the session value in the application. From the above post you can see, how easy is to use session in the Laravel.

If you found any issue in using session, please do comment below and let me know, i shall try to solve them.

You can also check How to pass data to view in Laravel