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

EdsonOrdaz's avatar

how to use session between controllers?

I need to store data in each user's session so that I don't have to check the database every time I need it. I need to read this information in several controllers, so I need to define it when starting the session.

I do it in the following way.

        if (Auth::attempt($credentials)) {

            session(['key' => 'value']);
        }

and to read it in another controller I define it like this

    public function test(Request $request){
        dd(session('key'));
    }

but the result is null, how could I do it?

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

The solution to this problem is to make sure that the session is started before setting or getting any values from it. In Laravel, the session is started automatically, but if you are using a custom session driver, you may need to manually start the session.

To set a value in the session, you can use the session() helper function or the Session facade. To get a value from the session, you can use the session() helper function or the Session facade.

Here's an example of how to use the session between controllers:

In the first controller:

if (Auth::attempt($credentials)) {
    session(['key' => 'value']);
}

In the second controller:

public function test(Request $request)
{
    if ($request->session()->has('key')) {
        dd($request->session()->get('key'));
    }
}

Make sure that the session middleware is applied to all routes that use the session. You can do this by adding the middleware to the $middleware property of the App\Http\Kernel class:

protected $middleware = [
    // ...
    \Illuminate\Session\Middleware\StartSession::class,
];
1 like

Please or to participate in this conversation.