Looking to hire Laravel developers? Try LaraJobs

query-builder-for-laravel maintained by roundly-consulting

Description
Native, allow-list-driven filter, sort and pagination for Laravel API list endpoints
Last update
2026/10/03 19:57 (dev-main)
License
Downloads
2

Comments
comments powered by Disqus

Query Builder for Laravel

Allow-list-driven filtering, sorting and pagination for Laravel API list endpoints. It reads the query string (filter[...], sort=, page, per_page) and applies only the filters and sorts a controller explicitly permits — anything else is rejected with a 400.

Installation

Requires PHP 8.4, Laravel 12 or 13.

composer require roundly-consulting/query-builder-for-laravel

Usage

Declare what a list endpoint may filter and sort, then use it like any Eloquent builder:

use RoundlyConsulting\QueryBuilder\AllowedFilter;
use RoundlyConsulting\QueryBuilder\AllowedSort;
use RoundlyConsulting\QueryBuilder\QueryBuilder;

// GET /posts?filter[status]=published,draft&filter[title]=laravel&sort=-popularity&per_page=50
public function index(ListPostsRequest $request)
{
    return QueryBuilder::for(Post::class)
        ->allowedFilters(
            AllowedFilter::exact('status'),                   // a comma list becomes whereIn
            AllowedFilter::partial('title'),                  // escaped LIKE, ILIKE on Postgres
            AllowedFilter::scope('published', booleans: true),
            AllowedFilter::trashed(),
        )
        ->allowedSorts('title', AllowedSort::field('popularity', 'views'))
        ->defaultSort('-created_at')
        ->paginate($request->perPage());
}

HasPageSize validates per_page on the form request — above the configured maximum is a 422:

use Illuminate\Foundation\Http\FormRequest;
use RoundlyConsulting\QueryBuilder\Concerns\HasPageSize;

final class ListPostsRequest extends FormRequest
{
    use HasPageSize;

    public function rules(): array
    {
        return $this->pageSizeRules();
    }
}

Documentation

The full documentation — configuration, every feature and its API, and testing — lives on our website: roundly-consulting.com/open-source/docs/query-builder-for-laravel

Release notes are in CHANGELOG.md. To contribute, see the contributing guide.

Support our work

This package is free and open source, built and maintained by Roundly Consulting. If it saves you time, please consider supporting our open-source work — a one-time donation, a monthly pledge on Patreon or a crypto donation helps fund maintenance, new features and new packages.

License

The MIT License (MIT). Please see LICENSE.md. Maintained by roundly-consulting.