简体   繁体   English

如何从laravel中的会话数组中删除项目

[英]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 这实际上是一个包含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? 现在我要删除让我们说4我该怎么做? I tried method 我试过方法

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

But it didn't work! 但它不起作用!

Other solution 其他方案

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

it also didn't work 它也没用

You AFAIR have to firstly retrieve whole array, edit it and then set it again. 您AFAIR必须首先检索整个数组,编辑它然后再次设置它。 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) 如果要按产品ID删除,这是我假设的数组值,您可以使用: PHP数组按值删除(不是键)

$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. Session::pull在项目删除时获取第一个参数,第二个参数作为要返回的默认值。 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需要字符串或数组,所以你应该只指定第一个参数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM