A Laravel package to implement filtering by request parameters.
example.com/json?name=Koen&sortBy=name&desc=0
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());
}
}