devmakerlab/laravel-filters

v1.4 2024-01-26 11:25 UTC

This package is auto-updated.

Last update: 2024-10-26 13:11:22 UTC


README

Build Status Code Coverage Latest Version on Packagist

DevMakerLab/Laravel-Filters

Need some filters? This package is based on the Repository Design Pattern to let you create specific queries easily.

Installation

⚠️ Requires >= PHP 7.4 ⚠️

composer require devmakerlab/laravel-filters

Usage

This package offers an abstract class AbstractFilterableRepository which needs to be extended to implement the features of this package.

PeopleService.php

<?php
    ...
    $peopleRepository = new PeopleRepository($databaseManager);
    
    $people = $peopleRepository
            ->addFilter(OldPeopleFilter::class)
            ->get(['age' => 60]);

OldPeopleFilter.php

<?php

declare(strict_types=1);

use Illuminate\Database\Query\Builder;
use DevMakerLab\LaravelFilters\AbstractFilter;

class OldPeopleFilter extends AbstractFilter
{
    public int $age;

    public function apply(Builder $queryBuilder): void
    {
        $queryBuilder->where('age', '>=', $this->age);
    }
}

PeopleRepository.php

<?php

declare(strict_types=1);

use DevMakerLab\LaravelFilters\AbstractFilterableRepository;

class PeopleRepository extends AbstractFilterableRepository
{
    private DatabaseManager $databaseManager;

    public function __construct(DatabaseManager $databaseManager)
    {
        $this->databaseManager = $databaseManager;
    }

    public function get(array $args): array
    {
        $queryBuilder = $this->databaseManager->table('people')
            ->select(['firstname', 'lastname', 'age', 'gender']);

        $this->applyFilters($queryBuilder, $args);

        $people = $queryBuilder->get();

        return $this->transform($people);
    }

    public function transform(Collection $people): array
    {
        $people->transform(function ($person) {
            return [
                'name' => sprintf('%s %s', $person->lastname, $person->firstname),
                'age' => $person->age,
                'gender' => $person->gender,
            ];
        });

        return $people->toArray();
    }
}

Example

Usage Example of DevMakerLab/Laravel-Filters package.