How to remove an item from session array in laravel

瘦欲@ 提交于 2019-11-29 15:27:13
Albert221

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');

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!