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

ycsm's avatar
Level 1

Session in laravel not storing

Hi all. I'm trying to set a session variable in Laravel 8.

    public function switchCentre(Request $request)
    {
        $centre = Centre::find($request->id);
 
        if($centre) {
            if($centre->id!==auth()->user()->centre_id){
                session(['centre' => $centre]);
                dd(session(['centre' => $centre]));
            }
            $msg = 'Switching centre...';
            return response()->json(['msg' => $msg], 200);
        }
   
    }

When I dump the session, it just throws me back NULL. If I dump the $centre variable, it gives me the correct array I'm expecting:

 "id" => 2
    "name" => "Joe Bloggs Business"
    "perm_project_management" => 1
    "perm_meetings" => 1
    "perm_personal_development" => 1
    "perm_qed" => 1
    "perm_reporting" => 1
    "perm_self_evaluation" => 1
    "perm_send" => 1
    "perm_rap" => 1
    "perm_activities" => 1
    "perm_finance" => 1
    "perm_human_resources" => 1
    "perm_vacancies" => 1
    "updated_at" => "2023-09-13 13:27:51"
    "created_at" => "2023-07-19 11:19:29"

I can't for the life of me figure out why the session isn't being stored. Am I missing something obvious here?

0 likes
4 replies
tykus's avatar

You are returning a JSON response; is this an API endpoint (in the api routes)? The Session would not be started in that case

1 like
JussiMannisto's avatar
Level 50

@tykus Has a point.

But also: when you say you're dumping the session, are you referring to the dd() call that's in your code? Calling session(['centre' => $centre]) sets a value, it doesn't return anything. So calling dd() on the result will show null.

If you want to read the value, use session('centre') or session()->get('centre'). Or if you want everything, use session()->all().

1 like
ycsm's avatar
Level 1

Hi both

@tykus - it was an APi end point, but within web routes as I'm using VueJS. So I tried a different way, I returned a view afterwards, and tried a redirect. And still getting NULL.

@jussimannisto - aha, silly me! I was using session(['centre']) by mistake like you said. Damn. It's no working. Thank you

Please or to participate in this conversation.