How to Implement OR Conditions with Laravel Collection

Laravel Laravel

When working with Laravel’s Collection, you may need to filter data using OR conditions. While Laravel provides an easy-to-use filter() method, it only supports AND conditions by default. This article will show you how to implement OR conditions effectively.

Understanding the filter() Method

Laravel’s filter() method is a powerful way to filter collections based on a given condition. However, it works with AND logic, meaning that multiple conditions must all be true for an item to be included in the final collection.

例えば、個数が10個以上または総額1万円以上の注文を抽出したいなど、OR条件を使いたいケースは様々あると思います。

Example of AND Condition Filtering

$collection = collect([
    ['name' => 'Alice', 'age' => 25],
    ['name' => 'Bob', 'age' => 30],
    ['name' => 'Charlie', 'age' => 35],
]);

$filtered = $collection->filter(function ($item) {
    return $item['name'] === 'Alice' && $item['age'] === 25;
});

// Only Alice remains in the collection

Implementing OR Conditions

To apply OR conditions, we need to modify the filter() method to allow an item to pass if at least one condition is met.

Using Multiple Conditions

$filtered = $collection->filter(function ($item) {
    return $item['name'] === 'Alice' || $item['age'] === 30;
});

This will return both Alice (who matches by name) and Bob (who matches by age).

Alternative Approach: Using reject()

If you prefer, you can use reject() to remove unwanted items instead:

$filtered = $collection->reject(function ($item) {
    return !($item['name'] === 'Alice' || $item['age'] === 30);
});

This approach keeps only the items that match the OR conditions.

Simplifying with whereIn()

If you are filtering by specific values in a field, whereIn() is a cleaner approach:

$filtered = $collection->whereIn('name', ['Alice', 'Bob']);

This selects all items where the name is either Alice or Bob.

Conclusion

Laravel’s Collection is a versatile tool, but handling OR conditions requires a bit of extra logic. By leveraging filter(), reject(), and whereIn(), you can efficiently filter collections based on your requirements.

コメント

Copied title and URL