PHP code example of devmakerlab / laravel-filters

1. Go to this page and download the library: Download devmakerlab/laravel-filters library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

devmakerlab / laravel-filters example snippets



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



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);
    }
}



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();
    }
}