Session

Store Data

Via a request instance

$request->session()->put('key', 'value');

Via the global "session" helper

session(['key' => 'value']);

Push a new value onto a session value that is an array

// array of team names
$request->session()->push('user.teams', 'developers');

Retrieving Data

#Via Request

// ...
class UserController extends Controller
{
    public function show(Request $request, $id)
 {
        $value = $request->session()->get('key');
        //
    }
}

Pass a default value as the second argument to use if the key does not exist

$value = $request->session()->get('key', 'default');
// closure can be passed and executed as a default
$value = $request->session()->get('key', function () {
    return 'default';
});

#Via session helper

Route::get('/home', function () {
    // Retrieve a piece of data from the session...
    $value = session('key');
    // Specifying a default value...
    $value = session('key', 'default');
    // Store a piece of data in the session...
    session(['key' => 'value']);
});

See: Session Helper

#All Session Data

$data = $request->session()->all();

#Retrieve and Delete

Retrieve and delete an item from the session

$value = $request->session()->pull('key', 'default');

Check Isset / Exists

Returns true if the item is present and is not null:

if ($request->session()->has('users')) {
    //
}

Returns true if present, even if it's null:

if ($request->session()->exists('users')) {
    //
}

Returns true if the item is null or is not present:

if ($request->session()->missing('users')) {
    //
}
Comments