How to Create and Delete Session in Laravel

AuthorSumit Dey Sarkar

Pubish Date22 Mar 2023

categoryLaravel

In this tutorial we will learn how to create and delete session in Laravel.

 

How to create and delete session in Laravel

In Laravel, a session allows you to store data across multiple requests. Sessions are managed using the session helper function and stored in the storage/framework/sessions directory by default. Here's how you can create and delete sessions in Laravel:

Creating a Session

To create a session in Laravel, you can use the put method of the session helper. Here's an example:

// Store a value in the session
session()->put('key', 'value');

 

You can also store multiple values in the session using an array:

// Store multiple values in the session
session()->put([
    'key1' => 'value1',
    'key2' => 'value2'
]);

 

Retrieving a Session Value

To retrieve a value from the session, you can use the get method of the session helper. Here's an example:

// Retrieve a value from the session
$value = session()->get('key');

If the value doesn't exist in the session, the get method will return null.

 

Deleting a Session

To delete a session value, you can use the forget method of the session helper. Here's an example:

// Remove a value from the session
session()->forget('key');

 

You can also delete the entire session data by using the flush method:

// Remove all session data
session()->flush();

 

Note: Deleting the session data using the flush method will remove all values from the session, not just the one you specify.

Comments 0

Leave a comment