HTTP is a stateless protocol — it has no built-in way to retain information between requests. Laravel’s session feature provides a way to store data about a user across multiple requests.You’ll use sessions for things like login state, shopping cart contents, and flash messages after form submissions.
// Retrieve by key$value = $request->session()->get('key');// Retrieve with a default value$value = $request->session()->get('key', 'default');// Default as a closure$value = $request->session()->get('key', function () { return 'default';});// Retrieve all session data$data = $request->session()->all();
// True if the key exists and is not nullif ($request->session()->has('user_id')) { // ...}// True if the key exists even if the value is nullif ($request->session()->exists('user_id')) { // ...}// True if the key is missingif ($request->session()->missing('user_id')) { // ...}
// Via the Request instance$request->session()->put('username', 'Alice');// Via the global helpersession(['username' => 'Alice']);// Append to an array stored in the session$request->session()->push('cart.items', ['id' => 1, 'name' => 'Widget']);
// Remove a specific key$request->session()->forget('username');// Remove multiple keys at once$request->session()->forget(['username', 'cart']);// Clear all session data$request->session()->flush();
Flash data is available only for the next request and then deleted automatically. It’s ideal for success messages, error notices, or any information that should be shown once.
// Keep all flash data for one more request$request->session()->reflash();// Keep specific keys for one more request$request->session()->keep(['status', 'message']);