If I try to remove an item from this collection
$examples = Example::where('example', '=', $data['example'])->get();
by doing
$examples->forget(20);
it doesn't remove the item from the collection, I still get back all the items that were in there originally. I have read the Laravel documentation and the api docs. And it should work (I think) but it doesn't.
Could someone point me out what I am doing wrong here?
This still returns an object.
$examples->forget(49);
return $examples->find(49);
P.S. Ever other method like push or get works.
Thanks alot!
You did a small mistake, actually you didn't notice that. I did myself :).
Forget
use the array key
to delete an object item from collection.
Array(0 => 'abc'
1 => 'bcd'
49 => 'aaa'
)
$examples->forget(49);
^^ array key 49
Where as, find
use the id
to find an object from an collection
table: examples
id example
1 abc
49 bce
$examples->find(49);
^^ `example id`
According to the documentation it says that forget()
works by key. The word "key" is ambiguous because what they mean to say is array key also known as "index" and not model key which is the id.
However, in the other methods such as find()
or contains()
they use the word "key" to mean model key so you can see the confusion.
When you look at the source you can see that the forget()
method is found in the Illuminate\Support\Collection
class and not in Illuminate\Database\Eloquent\Collection
.
My theory is that the support class is supposed to be more generic so it doesn't consider the model keys, but really I don't know.
I just wanted to add on to the Anam's answer. Once you have a collection you can then loop through it like this to delete by ID
function forgetById($collection,$id){
foreach($collection as $key => $item){
if($item->id == $id){
$collection->forget($key);
break;
}
}
return $collection;
}
$examples = Example::where('example', '=', $data['example'])->get();
$examples = forgetById($examples,20);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With