0
0
Laravelframework~5 mins

Session basics in Laravel

Choose your learning style9 modes available
Introduction

Sessions help remember information about a user while they browse your website. This way, the site can keep track of who they are and what they do.

Remembering if a user is logged in across different pages.
Storing items a user adds to their shopping cart.
Keeping track of user preferences like language or theme.
Saving temporary messages to show after a page reload.
Tracking form data temporarily to help with validation errors.
Syntax
Laravel
<?php
// Store data in session
session(['key' => 'value']);

// Get data from session
$value = session('key', 'default');

// Remove data from session
session()->forget('key');

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

Use the session() helper to easily work with session data.

You can store, retrieve, and remove data using simple methods.

Examples
This saves the name 'Alice' under the key 'username'.
Laravel
<?php
// Store user's name in session
session(['username' => 'Alice']);
This gets the username if it exists, otherwise returns 'Guest'.
Laravel
<?php
// Retrieve username or default to 'Guest'
$name = session('username', 'Guest');
This deletes the 'username' data from the session.
Laravel
<?php
// Remove username from session
session()->forget('username');
This removes everything stored in the session.
Laravel
<?php
// Clear all session data
session()->flush();
Sample Program

This example shows three routes: one to set a session value, one to get it, and one to clear all session data. When you visit /set-session, it saves 'blue' as the color. Visiting /get-session shows the saved color. Visiting /clear-session removes all session data.

Laravel
<?php
use Illuminate\Support\Facades\Route;

Route::get('/set-session', function () {
    session(['color' => 'blue']);
    return 'Session color set to blue';
});

Route::get('/get-session', function () {
    $color = session('color', 'no color set');
    return "The session color is: $color";
});

Route::get('/clear-session', function () {
    session()->flush();
    return 'Session cleared';
});
OutputSuccess
Important Notes

Sessions use cookies to link the user to their stored data.

Make sure your app has session middleware enabled to use sessions.

Session data is stored on the server, so it is safer than storing data in cookies.

Summary

Sessions keep user data while they browse your site.

Use session() helper to store, get, and remove data.

Clear sessions when you want to forget all stored info.