pavon147
pavon147

Reputation: 713

Laravel Collection keys modification

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!

Upvotes: 34

Views: 39314

Answers (2)

Lokman Hosen
Lokman Hosen

Reputation: 482

Here is the code

 // Just for demonstration
    $collection = collect([
        10 => ['fruit' => 'Apple', 'price' => 200],
        11 => ['fruit' => 'Mango', 'price' => 500]
    ]);

    $values = $collection->values();
    dd($values);

and Here is the result

items: array:2 [▼
0 => array:2 [▼
  "fruit" => "Apple"
  "price" => 200
]
1 => array:2 [▼
  "fruit" => "Mango"
  "price" => 500
]

]

Key start from 0.

Upvotes: 0

Saumya Rastogi
Saumya Rastogi

Reputation: 13703

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],
    ]
*/

Upvotes: 86

Related Questions