0

Through an ajax call with axios (ajax library) I set a session variable in Laravel 5.5:

session()->put('can_visit', true);

However, when I check in a next GET request (not with ajax) if that variable exists:

return session()->has('can_visit');

Result is always false, why is that? Is there a better way?

1 Answer 1

0

Just set it like this:

session(['can_visit' => true]);

Setting a default value for that key: (optional)

session('can_visit', false);

Check if it has a session with:

session()->has('can_visit');

Then fetch it with:

$canVisit = session('can_visit');
var_dump($canVisit);

Laravel is doing the heavy lifting for you:

function session($key = null, $default = null)
{
    if (is_null($key)) {
        return app('session');
    }

    if (is_array($key)) {
        return app('session')->put($key);
    }

    return app('session')->get($key, $default);
}
3
  • Thanks for your reply. But it's not working with an ajax call. Please see my code here: github.com/larsjanssen6/underconstruction/tree/master/src
    – Jenssen
    Sep 26, 2017 at 7:17
  • What debug did you try? dd($data) before every return and see whats return and what methods get called? Maybe its not a getting issue but a setting issue etc
    – emotality
    Sep 26, 2017 at 8:00
  • Yes, Ive done that couple of times but session variable does not exists anymore. So weird this.
    – Jenssen
    Sep 26, 2017 at 10:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.