where() and first()
Query items inside a collection with where() and grab one with first().
Syntax
$collection->where('key', 'value');The where() method filters a collection by a key/value pair, similar to a database WHERE clause. The first() method returns the first item, optionally matching a callback.
These read almost like plain English, which is a big part of why collections are so popular.
Example
Loading editor…
Press Run to execute the code.
When to use it
- A warehouse dashboard uses where() to filter a product collection to only in-stock items with a price below a given threshold.
- A notification service uses first() to retrieve the first unread message for the current user from a loaded collection.
- A cart system uses whereIn() to extract only the products whose IDs appear in the user's saved wishlist.
More examples
Filter by exact key-value match
where() performs a loose equality check on each item's 'role' key and returns only matching items.
$users = collect([
['name' => 'Alice', 'role' => 'admin'],
['name' => 'Bob', 'role' => 'editor'],
['name' => 'Carol', 'role' => 'admin'],
]);
$admins = $users->where('role', 'admin');
// => Alice, CarolGrab the first matching item
first() accepts a callback and returns the first element for which the callback evaluates to true, or null if none match.
$products = Product::all();
$featured = $products->first(fn($p) => $p->featured && $p->stock > 0);
// Returns the first featured, in-stock product or nullwhereIn() for multiple matching values
whereIn() filters the collection to items whose key value appears in the provided array, similar to SQL IN().
$wishlistIds = [3, 7, 12];
$wishlistItems = $products->whereIn('id', $wishlistIds);
// Only the three products whose id is in the list
Discussion