Using Session in Laravel

2024-04-24 02:37:23 Alok Laravel

Getting,Setting and Destroying session in Laravel

Sessions are used to store and pass information to one page to another page on website. It is a temporary storage and hold data for limited time.

Laravel sessions works similar to sessions created by other frameworks or programming languages. Laravel provides many inbuilt functions to work with sessions.

In Laravel, the session configuration file is stored at config/ session.php. By default, Laravel is configured to use the file session driver, which will work well for many applications. 

Set session variable in laravel

public function showProfile(Request $request, $id)  {
           
    $request->session()->put('key', 'value');

 }

Get session value in laravel

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

Retrieving all data from the session 

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

Checking if An Item Exists In The Session

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

Destroying session in Laravel

public function showProfile(Request $request, $id) {      
	 //Deleting Items From The Session
	 $request->session()->forget('key');
	 $request->session()->flush();    
 }

This post is submitted by one of our members. You may submit a new post here.

Related Tricks