Laravel Session

Sessions provide a way to store information across multiple requests. In laravel, the session configuration file is stored in 'app/config/session.php'.

You can pass session value across the different pages within same domain or website.

You do not need to handle $_COOKIE variable manually. Laravel do it by the smart way. Laravel provides some default method to handle the session.

Let’s see an example how you can create the session.

Session::put('key','value');
// OR
session()->put('key','value');
// OR
$request->session()->put('key','value');

Laravel store your session into key and value pair. You can use “Session” class or session() method both will work. Additionally, also you can use Request class object to handle the session. Once you store session you can get it using get() method.

Session::get('key');
// OR
session()->get('key');
// OR
$request->session()->get('key');

You can delete session by using forget method.

Session::forget('key');
// OR
session()->forget('key');

To remove all session you can use flush() method

Session::flush();
// OR
session()->flush('key');

To get all value of session you can use all() method.

Session::all();
// OR
session()->all();

Example:

class HomeController extends Controller
{
public function index(Request $request)
{
Session::put('framework','Laravel'); // To set Session Using Session class
Session::get('framework'); // To get Session Using Session class

session()->put('version',5.4); // To set Session Using session() method
session()->get('version'); // To get Session Using session() method

$request->session()->put('features', array('Method Injection','Authentication Scaffolding','Routing Requesut')); // To set Session Using session() method
$request->session()->get('features'); // To get Session Using session() method


// To remove session you can use forget() method
session()->forget('version');

// To remove all session you can use all() method
session()->flush();

}
}

If you are using file session You can take note that Laravel store unique file into storage/framework/sessions directory.

A directory contains the number of file with a unique name. Your information stored into serialize format into a file.

Leave a Reply

Your email address will not be published. Required fields are marked *