Session

These examples are using the Session facade. You can also use the session() helper function.

Storing Data

push(string $key, mixed $value) - add a value to an array

Session::push('users', 'Sam Smith');

put(string|array $key, mixed $value = null) - store or update data in the session

// Store a single key-value pair
Session::put('name', 'Mike Dingle'); 

// Store multiple key-value pairs
Session::put(['name' => 'Mike Dingle', 'age' => '30']);

// Store an array of values
Session::put('name', ['Mike Dingle', 'Sue Mcallen']);

Retrieve Session Data

all(): array - get all session data

$data = Session::all();

except(array $keys): array - get all session data except for specific keys

$data = Session::except(['username', 'email']);

get(string $key, mixed $default = null) - get a value from the session

// Get the value of a specific key
$username = Session::get('username');

// Get the value of a specific key, or a default value if the key is not present
$username = Session::get('username', 'default value');

// Get the value of a specific key, or execute a callback if the key is not present
$username = Session::get('username', function () {
    return 'default value';
});

only(array $keys): array - get a portion of the session data

$data = Session::only(['username', 'email']);

Removing Data

flush(): void - remove all session data

flush(): void

forget(string|array $keys): void - remove multiple key-value pairs

Session::forget(['username', 'email']);

pull(string $key, mixed $default = null) - remove a single key-value pair and return the value

$username = Session::pull('username');

remove(string $key) - remove a single key-value pair

Session::remove('username');

Item Existence

exists(string|array $key): bool - check if an item exists in the session, even if its value is null

has(string|array $key): bool - check if an item exists in the session and is not null

hasAny(string|array $key): bool - check if any of the items exist in the session

missing(string|array $key): bool - check if an item is missing from the session