Laravel collections have so many different methods, sometimes it's not always easy to know which one to use.
Consider this example, where we're parsing a flat array of key / value pairs:
$data = collect(['abc' => 'v1.0', 'xyz' => 'v2.0']);
// I want to know if $data contains a value of `xyz' => 'v2.0'
$result = $data->firstWhere('xyz', 'v2.0');
That seems like a logical use of firstWhere
: I want to find the first item "where" the key is 'xyz' and the value is 'v2.0'. Right?
This will not work, and it has to do with the shape of the collection we're searching.
firstWhere
(and many other methods that work with keys and values) are designed to work on a nested collection.
$data = collect([
['abc' => 'v1.0', 'xyz' => 'v1.0'],
['abc' => 'v2.0', 'xyz' => 'v2.0'],
]);
// this would work!
$result = $data->firstWhere('xyz', 'v2.0');
Why is this the case?
In order to answer that, we need to think about how a flat collection (or PHP array) works. It is not possible to have two items in a flat collection with the same key.
The last one defined will always overwrite the previous one:
$data = collect['abc' => 'v1.0', 'abc' => 'v2.0'];
// Illuminate\Support\Collection {
// #items: array:1 [
// "abc" => "v2.0"
// ]
// }
The duplicate item is gone! So understanding that, if I want to search a flat collection for a key / value pair, I can just retrieve the item by key and compare the value:
$data = collect(['abc' => 'v1.0', 'xyz' => 'v2.0']);
// no need for a "where" clause, because there can only be one value
$result = $data->get('xyz') === 'v2.0';
On the other hand, if it's a nested collection and I want to find the first one with a particular key / value pair, I do need a where clause, because more than one item could match.
I've found it very helpful to keep this basic principle in mind when working with collections: the shape of the data you're working with will determine which method you should use.
Taking a quick moment to reflect on the nature of PHP arrays, and by extension Laravel collections, leads us to that deeper understanding.
Here to help,
Joel
P.S. Laravel validation has even more rules than collections have methods. If you want deeper insights into which rules to use, download our book.