Ad

Set Session Variables In Laravel

- 1 answer

In vanilla PHP, I can set a session variable using the below code;

$_SESSION['blog'] = array(
    "email" => $_POST['email'],
    "password" => $password,
    "firstname" => $row ['firstName'],
    "lastname" => $row ['lastName'],
    "id" => $row ['id']
);

How can I do the same in laravel. FYI I'm not talking about the default session name eg PHPSESSID or laravel_session. I have multiple session variables for parts of my site such as web, blog, 'careers' and I name them just like the code above and able to check and access them individually. So one user can have all three sessions variables at the same time but for different sections of the site.

Ad

Answer

One way you could do it:

$vars = [
    "email" => $email,
    "password" => $password,
    "firstname" => $row['firstName'],
    "lastname" => $row['lastName'],
    "id" => $row['id']
];

session()->put('blog', $vars);

Laravel Docs - Session

Update: To check existence of a session variable:

session()->has('blog'); // bool

Update: To get an element contained in the session variable 'blog'

session('blog.id'); // using the dot notation
Ad
source: stackoverflow.com
Ad