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

Try it yourself
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.

Example · php
$users = collect([
    ['name' => 'Alice', 'role' => 'admin'],
    ['name' => 'Bob',   'role' => 'editor'],
    ['name' => 'Carol', 'role' => 'admin'],
]);

$admins = $users->where('role', 'admin');
// => Alice, Carol

Grab 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.

Example · php
$products = Product::all();

$featured = $products->first(fn($p) => $p->featured && $p->stock > 0);
// Returns the first featured, in-stock product or null

whereIn() for multiple matching values

whereIn() filters the collection to items whose key value appears in the provided array, similar to SQL IN().

Example · php
$wishlistIds = [3, 7, 12];

$wishlistItems = $products->whereIn('id', $wishlistIds);
// Only the three products whose id is in the list

Discussion

  • Be the first to comment on this lesson.