In Laravel, sessions provide a way to store information across multiple HTTP requests for a particular user. Sessions are commonly used to store user authentication status, flash messages, and other temporary data. Here's how you can work with sessions in Laravel
Laravel manages sessions transparently for you. You don't need to explicitly start a session. Laravel handles it automatically for every incoming request.
You can store data in the session using the session()
helper function or the Session
facade:
// Using session() helper function
session(['key' => 'value']);
// Using Session facade
use Illuminate\Support\Facades\Session;
Session::put('key', 'value');
You can retrieve data from the session using the session()
helper function or the Session
facade:
// Using session() helper function
$value = session('key');
// Using Session facade
$value = Session::get('key');
Flash data is session data that is available only for the next request and then automatically deleted from the session. It's commonly used for displaying temporary messages to users.
// Flashing data using session() helper function
session()->flash('message', 'This is a flash message.');
// Flashing data using Session facade
Session::flash('message', 'This is a flash message.');
You can retrieve flash data using the same methods as retrieving regular session data. However, flash data will be available only for the next request.
$message = session('message');
To remove data from the session, you can use the forget()
method:
// Remove a single key from the session
session()->forget('key');
// Remove multiple keys from the session
session()->forget(['key1', 'key2']);
// Remove all data from the session
session()->flush();
You can check if a key exists in the session using the has()
method:
if (session()->has('key')) {
// Key exists in the session
} else {
// Key does not exist in the session
}