Laravel 8 session syntax copypasta
As seen in: https://github.com/alexeymezenin/laravel-best-practices#use-shorter-and-more-readable-syntax-where-possible
There are 3(!) ways to interact with session data in Laravel now.
// option 1 - use facade
Session::get('cart')
// option 2 - use from request
$request->session()->get('cart')
// option 3 - use global function
session('cart')
I’m going with the shortest one.
// Example - non-array session operations
session(['name' => 'Eka']); // write
session()->forget('name'); // delete
return session('name') ?? 'anon'; // read
// Example - array session operations
$userData = ['id' => 123, 'name' => 'eka'];
session(['user' => $userData]);
session()->push('user.locations', 'bar');
session()->push('user.locations', 'baz');
session()->forget('user.locations');
dd(session('user') ?? 'no user');
Import the facade class with use Illuminate\Support\Facades\Session
.
Docs: https://laravel.com/docs/8.x/session
See also: Laravel 8 cache syntax
In: Laravel MOC