Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Collection keys modification

Tags:

I use filter method from Collection class to remove some objects from collection. But after that operation, sometimes objects with keys eg. 1, 4, 5 left. I would like to always have elements with order 0, 1, 2, 3 etc. after filter action.

Is there any elegant way to do it without rewriting table to a new one?

Thanks!

like image 631
pavon147 Avatar asked Nov 12 '16 23:11

pavon147


1 Answers

You can use Laravel Collection's values() method to make the the keys of a collection in a serialized order like this:

// Just for demonstration $collection = collect([     10 => ['fruit' => 'Apple', 'price' => 200],     11 => ['fruit' => 'Mango', 'price' => 500] ]);  $values = $collection->values();  $values->all();  /* Result would be:     [         0 => ['fruit' => 'Apple', 'price' => 200],         1 => ['fruit' => 'Mango', 'price' => 500],     ] */ 
like image 65
Saumya Rastogi Avatar answered Oct 06 '22 23:10

Saumya Rastogi