Alen
Alen

Reputation: 1291

How to remove an item from session array in laravel

Here is the problem I have a session

session('products')

this is actually an array that contains id

session('products')
array:4 [▼
0 => "1"
1 => "2"
2 => "4"
3 => "1"
]

Now I want to delete lets say 4 How do I do that? I tried method

session()->pull($product, 'products');

But it didn't work!

Other solution

session()->forget('products', $product);

it also didn't work

Upvotes: 4

Views: 22916

Answers (5)

Abass Iddrisu
Abass Iddrisu

Reputation: 1

    $value = session('shopping_cart', 'default'); // Get the array
    unset($value[$key]); // Unset the index you want
    session(['shopping_cart' =>$value ]);// Set the array again

Upvotes: 0

anoraq
anoraq

Reputation: 515

Was looking for this functionality as well but ended up doing it like this. Since it's by value you want to remove, this method is also built for removing multiple products in one hit!

For example; removing productIds 5, 11 and 541 from a cart with products)...

// Get the current session products
$products = session()->get('products');

// Remove certain products
$products = array_diff($products, [5, 11, 541]);

// Set the session with the new altered products
session()->put('products', $products);

Upvotes: 0

Dennis Martel
Dennis Martel

Reputation: 21

You can do it in the following way in case you have a function to delete an item from a cart

public function deleteProductoCart(Producto $producto) {
    $cart = \Session::get('products');
    unset($cart[$producto->id]);
    \Session::put('products', $cart);
    return redirect()->route('tu-ruta');
}

Upvotes: 0

Albert221
Albert221

Reputation: 7082

You AFAIR have to firstly retrieve whole array, edit it and then set it again. If you want to delete by product ID, which is as I assume an array value, you can use this: PHP array delete by value (not key)

$products = session()->pull('products', []); // Second argument is a default value
if(($key = array_search($idToDelete, $products)) !== false) {
    unset($products[$key]);
}
session()->put('products', $products);

Misunderstood question

Session::pull takes first parameter as the item do delete and second as the default value to return. You have mistaken the order of arguments. Try:

session()->pull('products'); // You can specify second argument if you need default value

As I can see in source, Session::forget expects string or array, so you should specify only the first parameter:

session()->forget('products');

Upvotes: 20

This method isn't tested:

Session::forget('products.' . $i);

note the dot notation here, its worth the try. If that isnt working, you can always do this:

$products = Session::get('products'); // Get the array
unset($product[$index]); // Unset the index you want
Session::set('products', $products); // Set the array again

Upvotes: 5

Related Questions