how do I delete an item in session that is in an array I am pushing to array session values like this
$request->session()->push('test', '1');
$request->session()->push('test', '2');
$request->session()->push('test', '3');
When I want to delete a normal item in session I can do it like this:
$value = $request->session()->pull('key');
but how do I delete from session item, for example in test array above specific item lets say with value 2?
thanks @jekinney
I did it like this for anyone else wondering in future:
$images = Session::get('image');
$found = null;
foreach ($images as $key => $value) {
if($value == $request->image) {
$found = $key;
@unlink ($request->image);
}
}
// reset image array
Session::pull('image');
if($found)
unset($images[$found]);
Session::put('image', $images);
Try to use '.' to access array elements.
$value = $request->session()->pull('test.2');
@Organizm238 you mean
$request->session()->pull('test.2');
would that work? it would be better then my solution.
@maxnb yes, sory, i meant 'pull' . I just can't test it right now, but from the laravel docs it should work.
UPDATE:
I've tested it, it works.
session()->push('test', '1');
session()->push('test', '2');
session()->push('test', '3');
session()->pull('test.2');
dd(session()->all());
"test" => array:2 [▼
0 => "1"
1 => "2"
]
Remember that test.2 finds element with a key=2, not with a value. So code above removes element with value '3'.
New answer
I think it would be easier to store a collection instead of an array, which gives you all the of the Collection features
session(['test'=>collect([])]);
And then for any modification, you are able to handle a normal collection
Ex: to delete an item by its value:
$key = session('test')->search(1);
session('test')->forget($key);
Please sign in or create an account to participate in this conversation.