The FilteringUtil
in the LaraUtilX
package provides functionality for filtering collections based on key-value pairs using various comparison operators.
filter(Collection $items, string $name, string $operator, $value): Collection
: Filters a collection by a given key-value pair.Filter Collection:
To filter a collection, use the filter
method:
use omarchouman\LaraUtilX\Utilities\FilteringUtil;
use Illuminate\Support\Collection;
$collection = new Collection([
['id' => 1, 'name' => 'John'],
['id' => 2, 'name' => 'Jane'],
['id' => 3, 'name' => 'Doe']
]);
$filteredCollection = FilteringUtil::filter($collection, 'name', 'contains', 'John');
Comparison Operators: The filter method supports various comparison operators:
equals
: Check if the value of the specified key equals the provided value.not_equals
: Check if the value of the specified key does not equal the provided value.contains
: Check if the value of the specified key contains the provided substring (case-insensitive).not_contains
: Check if the value of the specified key does not contain the provided substring (case-insensitive).starts_with
: Check if the value of the specified key starts with the provided substring (case-insensitive).ends_with
: Check if the value of the specified key ends with the provided substring (case-insensitive).The utility returns a new collection containing only the items that match the filtering criteria.
Success Result:
Failure Result:
This utility simplifies the process of filtering collections, providing a convenient way to extract relevant data from a collection based on specified conditions.