#development #laravel #pattern #php

I'm a big fan of using collections in Laravel.

When you filter a collection in Laravel, you might have noticed that it keeps the original array indexes.

Imagine you have the following collection:

1$collection = collect([
2    1 => ['fruit' => 'Pear', 'price' => 100],
3    2 => ['fruit' => 'Apple', 'price' => 300],
4    3 => ['fruit' => 'Banana', 'price' => 200],
5    4 => ['fruit' => 'Mango', 'price' => 500]
6]);

When you filter the collection to retrieve all elements with a price higher than 200, you get:

1$filtered = $collection->filter(fn ($item) => $item['price'] > 200)->all();
 1[
 2    2 => [
 3        "fruit" => "Apple",
 4        "price" => 300,
 5    ],
 6    4 => [
 7        "fruit" => "Mango",
 8        "price" => 500,
 9    ],
10]

PS: I'm using the all method to get the result as a plain array.

Notice that the indexes are preserved. Sometimes, this can be annoying. There is however an easy fix by using the values method on the collection after the filtering.

1$collection->filter(fn ($item) => $item['price'] > 200)->values()->all();
 1[
 2    [
 3        "fruit" => "Apple",
 4        "price" => 300,
 5    ],
 6    [
 7        "fruit" => "Mango",
 8        "price" => 500,
 9    ],
10]