Search code examples
collectionslaravel

Forget doesn't work


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!


Solution

  • You did a small mistake, actually you didn't notice that. I did myself :).

    Forget uses the array key to delete an object item from a collection.

    Array(0 => 'abc'
     1 => 'bcd'
     49 => 'aaa'
    )
    
    $examples->forget(49);
                      ^^ array key 49
    

    Whereas, find uses the id to find an object from a collection

    table: examples
    
    id example
    1   abc
    49  bce
    
    $examples->find(49);
                    ^^ `example id`