Laravel Session

What is Session?

In Laravel, session is a parameter passing mechanism which enable us to store data across multiple requests. Session allows us to keep track of visitor across application. Laravel uses a driver based system for session management, each of the driver is used to define where the session data will be stored. Laravel framework have following in-built session drivers –

file – Session data is stored in an encrypted file located at storage/framework/sessions.
cookie – Session data is stored in secure and encrypted user’s cookies.
database – Session data is stored in application database.
apc – Session data is stored in APC.
memcached – Session data is stored in Memcached.
redis – Session data is stored in Redis.
array – Session data is stored in a PHP array, but it is not persisted across the requests.

Laravel session configuration file is located at “app/config/session.php“. If you don’t specified your session driver, then by default file driver is used.

Storing Data In The Session

Using put method of Request instance we can store data in the session, it accepts two arguments the “key” and “value“.

Syntax:-

Example:-

Retrieving Value from Session

Using get method of Request instance we can retrieve a single value from the session, it accepts two arguments the “key_name” and “default_value“.

Syntax:-

OR

Second argument of the get method is the default value which will be returned if your specified key does not exist in the session.

Example:-

Retrieving All Session Data

Using all method of Request instance we can retrieve all the available data in the session.

Syntax:-

Checking If an Item Exists In Session

Using has method you can determine if a value is present in the session, it returns true if the value is present in the session and null if doesn’t present.

Syntax:-

Example:-

Deleting Data from session

Using forget method you can remove the specified item from the session, it accepts “key” as argument.

Syntax:-

If you want to retrieve an item value before deleting it from the session, you can use the pull method.

Syntax:-

If you want to remove all items from the session, you can do it using flush method.

Syntax:-

Add Array In Session

If you want to add array into session, you can do it using push method as following –

Syntax:-

Example:-

Regenerating Session ID

If you want to regenerate the session ID, you can do it using regenerate method.

Flash Data

If you want to store items in the session that will be available for only next request.You can do it using the flash method, flash data is available only for the subsequent HTTP request, and then will be deleted.

Syntax:-

Example:-