koenhoeijmakers/laravel-filterable

Explicit request filtering.

v6.0.0 2023-02-27 09:05 UTC

README

Build Packagist Packagist license

A Laravel package to implement filtering by request parameters.

example.com/json?name=Koen&sortBy=name&desc=0

Usage

Require the package.

composer require koenhoeijmakers/laravel-filterable

Inject it in your controller (or resolve it from the container in any other way).

namespace App\Http\Controllers\Api\User;

use KoenHoeijmakers\LaravelFilterable\Contracts\Filtering;

final class Index
{
    public function __construct(
        private readonly Filtering $filtering
    ) {}

    public function __invoke()
    {
        $builder = User::query();
        
        $this->filtering->builder($builder)
            ->filterFor('name', fn(Builder $builder, string $value) => $builder
                ->where('name', 'like', "{$value}%");
            )
            ->sortFor('name')
            ->defaultSorting('name')
            ->filter();
    
        return UserResource::collection($builder->paginate());
    }
}