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

princelionelnzi's avatar

Content of a session always return null

I am working on a add to compare list system. The main idea is to put all the items which have been added to the compare list to a session.

This is the code I have been working on:

<?php

namespace App\Modules\MFilter\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Feature;
use App\Models\Offer;
use Illuminate\Http\Request;
use Session;
use Validator;

class FilterController extends Controller
{
    public function addToCompare(Request $request) {

        $offer_id = $request['offer_id'];

        $offer = Offer::find($offer_id);

        if ($offer){
            $old = session('compare') ? session('compare') : null;

            // Display the old content of the session
            dump('Old value: ');
            dump(session('compare'));
            
            $old[$offer_id] = $offer;
            $compare = $old;

            session(['compare' => $compare]);


            // Display the new content of the session
            dump('New value: ');
            dump(session('compare'));
        }
    }
}

This code $old = session('compare') ? session('compare') : null; is supposed to return the old content of the session but it is always returning `null.

But as soon as I add a content to the session and check the content of the session, I am getting the item which was lastly added.

I access the code above by using this route:

Route::group([
    'prefix' => '/filter',
    'namespace' => 'App\Modules\MFilter\Controllers',
],

    function() {

        Route::get('compare/add',  ['as' => 'filter.compare.add', 'uses' => 'FilterController@addToCompare']);
       
    }
);

Kindly help me fix this problem.

0 likes
0 replies

Please or to participate in this conversation.