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

t0berius's avatar

laravel session array (delete entry)

Trying to store the last visited products into an array inside the user session:

            //check if we would reach 5 items
            if(count($request->session()->get('last_products')) + 1 >= 5){
                $request->session()->pull('last_products.4');
                $request->session()->push('last_products', $product->id);
            }
    //first time to store
            else
                $request->session()->push('last_products', $product->id);

For sure, the current code won't work, since the position of the array (4) is hardcoded. Any idea how to get this done, so only the last 5 visited product ids are being stored? Oldest one should be deleted first.

0 likes
12 replies
s4muel's avatar

store whole $visited array into the session, here is what i mean:

//get the `visited` (array) from session, or return default empty array, if it doesnt exist
$visited = request()->session()->pull('visited', []);

//dump it, so you can see it
dump($visited);

//push your visited product to the end of the array (just random int in our example)
array_push($visited, rand(1, 1000));

//get the last 5 items of the end of the array
$visited = array_slice($visited, -5);

//save the updated $visited array to the session
session(['visited' => $visited]);
jlrdw's avatar

@jaheller check this out, works:

        Session::push('company.name', 'Acme Widgets');
        Session::push('company.phone', '915-999-9999');

        $myarray = Session::get('company');
        var_dump($myarray);

        Session::forget('company.phone');
        $myarray = Session::get('company');

        var_dump($myarray);

Second var dump does not have phone.

//first
array(2) { ["name"]=> array(1) { [0]=> string(12) "Acme Widgets" } ["phone"]=> array(1) { [0]=> string(12) "915-999-9999" } }

//second
array(1) { ["name"]=> array(1) { [0]=> string(12) "Acme Widgets" } } 

Pull also works:

       Session::push('company.name', 'Acme Widgets');
        Session::push('company.phone', '915-999-9999');
        var_dump(Session::get('company'));
        
        Session::pull('company.phone');
        var_dump(Session::get('company'));
t0berius's avatar

@s4muel

Your example doesn't take care of deleting entries?

@jlrdw

See my array above, it's not multidimensional at all.

jlrdw's avatar

since the position of the array (4) is hardcoded

Re-create session array with the newest 5.

And name value pairs might help, I'm not sure.

t0berius's avatar

@JLRDW - So you mean deleting the whole array and creating it from scratch new (inserting every id again)?

jlrdw's avatar

If you are removing say 2 products in the array with 7, it leaves 5. Which is what you want. Can you dd it and show results.

You need to use array keys, much easier.

Trying to get example:

An array first:

$company = array(
            "name" => 'Acme Widgets',
            "phone" => '915-999-9999'
        );
        
        Session::put('company', $company);
        

        foreach (Session::get('company') as $key => $value) {
            echo $key . " : " . $value . "<br>";
        }

And:


$company = Session::get('company');
        
        
        unset($company['phone']);
        
        echo "<br>";
        echo "<br>";
        
        Session::put('company', $company);
        
        foreach (Session::get('company') as $key => $value) {
            echo $key . " : " . $value . "<br>";
        }

So yes just recreate session array from temp working array, just so much easier.

In a temp array you can use:

unset($array['key1']);
$company = Session::get('company');   //(temp array to work with)
        unset($company['phone']);
        echo "<br>";
        Session::put('company', $company);   //(back to session array)
        foreach (Session::get('company') as $key => $value) {
            echo $key . " : " . $value . "<br>";
        }
t0berius's avatar

I don't understand why you use a multidimensional array. I only need to store the last 5 visited ids of a product, no need for a multidimensional array at all.

jlrdw's avatar

Maybe then just remove elements (values from simple array.)

I'd still put the session array in an regular temp array to work with:

$temparray = array('item1', 'item2', 'item3', 'item4', etc, etc);


$temparray = array_diff($temparray, array('to_remove1', 'to_remove2', etc));


result is array with removed items

Then put back to session.

Array's can be tricky, I'd suggest you have in a development machine a scratch controller to play around with array's, collections, Json, etc for the trial and error it takes.

One array may be looped one way, yet another nested, another.

You may be able to use collections and play around there. I usually just use array's, same thing - collections is array helpers.

Also take a little time and play around with array_diff and array_splice.

I only need this stuff from time to time.

Snapey's avatar
Snapey
Best Answer
Level 122

Just pass the ID into this function

    private function addToHistory($item) 
    {
        $history = session()->pull('history',[]);

        array_push($history,$item);

        session()->put('history', array_slice($history, -5));
    }
1 like
Snapey's avatar

Be aware that this simple case does not take care of duplicates

t0berius's avatar

@snapey

Already included ;)

private function addToHistory($item)
{
    $history = session()->get('history',[]);
    //check if item already exists inside the current history
    if(!in_array($item, $history)){
        session()->pull('history',[]);
        array_push($history,$item);
        session()->put('history', array_slice($history, -5));
    }
}

Please or to participate in this conversation.