Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 433
vblinden Avatar asked Dec 22 '13 23:12

vblinden


3 Answers

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`
like image 191
Anam Avatar answered Nov 12 '22 02:11

Anam


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.

like image 3
rickshawhobo Avatar answered Nov 12 '22 02:11

rickshawhobo


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);
like image 2
Tyler Arbon Avatar answered Nov 12 '22 01:11

Tyler Arbon