Navigation

Laravel

How to Filter a Collection Based on a Key's Value

Master Laravel collection filtering with where(), whereIn(), and filter() methods. Find items matching specific criteria efficiently.

Problem: You have a collection and need to filter items where a specific key matches certain values, but you're unsure which method to use.

Solution:

$users = collect([
    ['name' => 'John', 'age' => 30, 'role' => 'admin'],
    ['name' => 'Jane', 'age' => 25, 'role' => 'user'],
    ['name' => 'Bob', 'age' => 30, 'role' => 'user'],
]);

// Filter by exact value
$admins = $users->where('role', 'admin');
$age30 = $users->where('age', 30);

// Filter by multiple values
$specific = $users->whereIn('role', ['admin', 'moderator']);
$adults = $users->whereIn('age', [25, 30, 35]);

// Filter with operators
$young = $users->where('age', '<', 30);
$notAdmin = $users->where('role', '!=', 'admin');

// Custom filter logic
$customFilter = $users->filter(function ($user) {
    return $user['age'] >= 25 && $user['role'] === 'user';
});

// Chain multiple filters
$result = $users->where('age', '>=', 25)
    ->where('role', 'user')
    ->values(); // Reset keys

Why it works: where() filters by exact match or with operators. whereIn() checks if the value exists in an array. filter() accepts a callback for complex logic. All methods return a new collection, leaving the original unchanged. Use values() to reset numeric keys after filtering.

Performance tip: For database records, filter at the query level before converting to a collection.

Table Of Contents

Related Topics

Share this article

Add Comment

No comments yet. Be the first to comment!

More from Laravel