Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

COACHTHEM's avatar

session not working in laravel 5.5

I am trying to set details of user in the session using global helper function session() . after setting session using session(['user' => ['id'=>1,'name'=>'my name']]); I am trying to access the user array from session on a different page like this $user_details = session('user'); Unfortunately I am not able to print the array. Below is my code

    public function index()
    {
        session(['user' => ['id'=>1,'name'=>'my name']]);
    }

    public function test()
    {
        $user_details = session('user');
        print_r($user_details);
    }
0 likes
5 replies
COACHTHEM's avatar

One thing I noticed that after setting the user details in index method and if I try to print it in the same method it works.

    public function index()
    {
        session(['user' => ['id'=>1,'name'=>'my name']]);

        $user_details = session('user');
        print_r($user_details); // THIS WORKS

    }

    public function test()
    {
        $user_details = session('user');
        print_r($user_details); // DOES NOT WORK.
    }
Snapey's avatar

try actually returning something from the index method after setting session.

COACHTHEM's avatar

Hi @Snapey

I am able to print the set session data in the index method but not able to access on other pages. Looks like the session is set only for one request

COACHTHEM's avatar

Thanks @Snapey

After setting the session I was printing it and doing exit below.. I tried removing the exit() statement and it did work. I am able to access the session data on other pages as well. Thanks.

Please or to participate in this conversation.