2

I have laravel application and I store items in a basket using the session.

function that adds item to basket

public function addItem($id)
    {
        session()->push('user.basket', $id);
        return back();
    }

function which removes item from basket

public function removeItem($id)
    {
        session()->pull('user.basket', $id);
        return back();
    }

When I add items this works fine, however when I come to remove an item that's in the basket the whole basket is removed?

2

2 Answers 2

1

The session()->pull('key','default') method removes the item with key, and returns the default value if it does not exist.

There is no way to delete item from array directly, you need to implement it:

$array = session()->pull('user.basket',[]);
unset($array[$id]);
session()->put('user.basket',$array);
Sign up to request clarification or add additional context in comments.

Comments

0

As you probably know, an array has values and each value has a key (['key1' => 'value1']), the value could also be another array. In your example, you have used an array (user.basket), each dot represents a new level of the array.

Remove by value

You push your ID to the session array. You don't specify any key and it will therefore get an unknown key, so you want to remove it using a value (your ID). The variable $valueToRemove in the example is your ID.

session()->put('user.basket', array_diff(session()->get('user.basket'), [$valueToRemove]));

To explain: Replace the user basket with everything in user basket that isn't in the array that only contains the $valueToRemove.

Remove by key

Lets say you know the which key (position) you want to remove, for example if you loop throw the array foreach(session()->get('user.basket') as $key => $value). Then you can remove the specific key using forget.

session()->forget('user.basket.'.$keyToRemove); // example: 'user.basket.7'

Your code

public function removeItem($id)
{
    session()->put('user.basket', array_diff(session()->get('user.basket'), [$id]))
    return back();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.