Php – Laravel 5 session not persisting after user is logged in

laravelphpsession

I'm having an interesting issue with Laravel 5.

After logging in a user, the logged in status is not persisted across pages. Clearly it has something to do with Session::.

The way I'm logging in a user is pretty straight-forward:

if (Auth::attempt(['email' => $data['email'], 'password' => $data['password']],
    isset($data['remember_me']) ? TRUE : FALSE))
{
    return redirect()->intended('/');
}

A simple print_r(Session::all()); gives me the following if the user is NOT logged in:

Array
(
    [_token] => wV8o75lZnCZ0f6CMMQgdBBM2AxSYjtWisAXx6TgZ
    [flash] => Array
        (
            [old] => Array
                (
                )

            [new] => Array
                (
                )

        )

    [_previous] => Array
        (
            [url] => http://localhost/public
        )

)

After the user is logged in an redirected to / the array looks like this:

Array
(
    [_token] => wV8o75lZnCZ0f6CMMQgdBBM2AxSYjtWisAXx6TgZ
    [flash] => Array
        (
            [old] => Array
                (
                )

            [new] => Array
                (
                )

        )

    [_previous] => Array
        (
            [url] => http://localhost/public/
        )

    [login_82e5d2c56bdd0811318f0cf078b78bfc] => 2
)

However, after any action that will lead to a page refresh or a redirect, the session status is lost.

My config/session.php file looks like so:

<?php

return [
    'driver' => env('SESSION_DRIVER', 'file'),
    'lifetime' => 120,
    'expire_on_close' => false,
    'encrypt' => false,
    'files' => storage_path('framework/sessions'),
    'connection' => null,
    'table' => 'sessions',
    'lottery' => [2, 100],
    'cookie' => 'laravel_session',
    'path' => '/',
    'domain' => null,
    'secure' => false,

];

The locally stored file for the session can be written and read.

I've tried using database drive instead of file. Same thing happens the [login_xx] => 2 key/value is lost and I'm logged out.

Since the Session:: is not completely reset I'm suspecting that I'm not logging in the user properly or simply doing something that I shouldn't be doing somewhere.

Best Solution

I faced similar issue, I simply called:

Session::save();

after any add/update/delete to Session storage. So it looked like:

$id = Input::get('id');
Session::forget('cart.' .$id);
Session::save();
Related Question