How To Set And Get Session Example In Laravel

Hello Artisan,

In this Laravel session tutorial, I will discuss Laravel session. I will show you how to set session, how to get session and how forgot session in Laravel application. You know that Session is useful to hide the data which the user can not be able to read or write.

Sessions are easier to handle in Laravel. Sometimes we need to store data in our session without saving it in the database. That case session is the best option to put this data somewhere. Like we want a create a session-based login system, or create an add to cart e-commerce option using session. 

Session stores data till the browser is opened, when the browser is closed, the session data is removed. There are two ways in Laravel to working with session, First is to Request instance and second use session() helper method.

We can put data in session like two ways. Like


// global session helper
session(['key' => 'value']);


Now if you would like to get session data, do it like below:

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

// global helper method
$value = session('key');

// return session data with default value if not specific session key not found
$value = session('key', 'default');


Now if you would like to fetch all session data, then follow this method:

$data = $request->session()->all();


You can also check session data like below before fetching it:

if ($request->session()->has('users')) {
    // 'user' key is in session
    $user = $request->session()->get('users');


If you also want to check if the session value exists or not, then use exist() method.

if ($request->session()->exists('users')) {
    // 'user' is exist in session
    $user = $request->session()->get('users');


Suppose sometimes we want to push value to exist session array, you can use push() method. This will set a new value for the framework's key of PHP array.

$request->session()->push('php.frameworks', 'laravel');


If you want to delete the session or forgot session then use this:



If we want to delete multiple session data, then pass an array of keys to forget() method.

$request->session()->forget(['key1', 'key2']);


If we want to delete all session data, then use flush() method.



Remember, we may manually regenerate the session ID, you may use the regenerate() method.



Read also: How to Change Default Session Lifetime in Laravel


Hope it can help you.

#laravel #laravel-8x