Filtering Utility

The FilteringUtil in the LaraUtilX package provides functionality for filtering collections based on key-value pairs using various comparison operators.

Methods

  1. filter(Collection $items, string $name, string $operator, $value): Collection: Filters a collection by a given key-value pair.

Usage

  1. 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');
  2. 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).

Result

The utility returns a new collection containing only the items that match the filtering criteria.


Success Result:

  • If any items in the collection match the specified conditions, the utility returns a new collection containing those items.

Failure Result:

  • If no items in the collection match the specified conditions, the utility returns an empty collection.


This utility simplifies the process of filtering collections, providing a convenient way to extract relevant data from a collection based on specified conditions.