We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
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:
<?php
$collection = collect([
1 => ['fruit' => 'Pear', 'price' => 100],
2 => ['fruit' => 'Apple', 'price' => 300],
3 => ['fruit' => 'Banana', 'price' => 200],
4 => ['fruit' => 'Mango', 'price' => 500]
]);
When you filter the collection to retrieve all elements with a price higher than 200, you get:
<?php
$filtered = $collection->filter(fn ($item) => $item['price'] > 200)->all();
<?php
[
2 => [
"fruit" => "Apple",
"price" => 300,
],
4 => [
"fruit" => "Mango",
"price" => 500,
],
]
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.
<?php
$collection->filter(fn ($item) => $item['price'] > 200)->values()->all();
<?php
[
[
"fruit" => "Apple",
"price" => 300,
],
[
"fruit" => "Mango",
"price" => 500,
],
]
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.