Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

php - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...