filter()

filter() keeps only the items that pass a truth test.

Syntax$collection->filter(function ($item) { return $condition; });

The filter() method returns a new collection containing only the items for which the callback returns true. If you call filter() with no callback, it removes all falsy values (like 0, null and '').

Use values() afterwards if you want to reset the keys to 0, 1, 2.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A user listing page filters a collection of accounts to show only those whose email address has been verified.
  • An e-commerce back-end filters a product collection to keep only items with stock greater than zero before rendering the catalog.
  • A reporting job filters transaction records down to those in the current month before aggregating totals.

More examples

Keep only even numbers

Filters the collection to keep only items for which the callback returns true (even numbers).

Example · php
$numbers = collect([1, 2, 3, 4, 5, 6]);

$evens = $numbers->filter(fn($n) => $n % 2 === 0);
// => Collection [2, 4, 6]

Filter verified users from Eloquent result

Removes unverified users from the collection by checking the email_verified_at timestamp.

Example · php
$verified = User::all()
    ->filter(fn($user) => ! is_null($user->email_verified_at));

$count = $verified->count();
// Number of verified users

Filter without a callback removes falsy values

Calling filter() with no callback discards all falsy values (0, '', null, false), preserving the original keys.

Example · php
$mixed = collect([0, 1, '', 'hello', null, false, true]);

$truthy = $mixed->filter();
// => Collection [1, 'hello', true]
// Keys are preserved; call ->values() to reindex

Discussion

  • Be the first to comment on this lesson.