Laravel PHP · Inline✓ Human-reviewed

Allowlisted API filters and sorting in Laravel PHP

Inline a bounded Query Builder slice: tenant-scoped exact and partial filters, safe sort aliases, deterministic pagination, and explicit rejection of unsupported inputs.

Approved 2026-12-04T12:03:48.228295Z · Submission 23

Allowlisted API filters and sorting in Laravel PHP

Scope and provenance

Reference: Spatie's MIT-licensed spatie/laravel-query-builder 7.3.10 at dee20864308f99258e462ebcf9b6eec2a1aafbb8. Inspect Concerns/FiltersQuery.php, Concerns/SortsQuery.php, Filters/FiltersPartial.php, Filters/FiltersExact.php, Sorts/SortsField.php, QueryBuilderRequest.php, and their tests under src/ and tests/. Retain upstream MIT attribution if adapting source. Laravel PHP baseline: 1b57d01aa866b042a75683bd9ef3517008c632fc.

This recipe replaces one endpoint's bounded filters and sorts, not the whole package. Example contract: filter[status] exact scalar, filter[name] literal case-insensitive substring, and sort=name,-created_at, with stable pagination. Exclude relationship filters/includes, custom operators, JSON paths, sparse fieldsets, aggregates, arrays/comma expansion, and user-selected columns until an actual caller requires them. The existing app's behavior wins over this example; list differences before changing its API.

Read the old behavior first

The package defaults string filters to partial matches, validates requested filter/sort names against allowlists, interprets a leading - as descending, and leaves the underlying Eloquent builder in place. Exact filter arrays can become whereIn; partial filters escape SQL LIKE wildcard characters and use bound values. Includes and field selection are separate contracts, not harmless extras. A tenant base query is an authorization boundary, not another optional client filter.

Inventory every QueryBuilder::for, allowedFilters, defaultFilter, allowedSorts, defaultSort, allowedIncludes, and allowedFields call on the affected endpoint. Capture its current status codes, empty/null/boolean behavior, comma rules, default order, pagination shape, and relationship constraints before replacing it.

Implement the smallest endpoint-owned adapter

  1. Validate a filter object with only status and name. Reject unknown keys and nested/array values. Bound string lengths, sort count, and page size. If clients already use arrays or nullable filters, either support that explicitly or keep this endpoint on the package; silently coercing values is not compatibility.
  2. Start from the authorized relationship/query, for example $tenant->users(). A supplied filter[tenant_id], include, or sort must never change ownership. Check endpoint policies before applying client input.
  3. Map status to a fixed enum and where('status', $value). For literal name search, use the app's verified helper or escape explicitly: $escaped = str_replace(['!', '%', '_'], ['!!', '!%', '!_'], mb_strtolower($name, 'UTF-8'));, then $query->whereRaw("LOWER(users.name) LIKE ? ESCAPE '!'", ['%'.$escaped.'%']);. The column is fixed, never request input. The explicit ! escape avoids driver-dependent backslash assumptions. whereLike($column, "%$name%") alone does not escape user wildcard characters. Verify Unicode/collation behavior on the production database, not only SQLite.
  4. Parse at most a small configured number of comma-separated sort tokens. A fixed alias map supplies column names; no request value becomes a raw SQL identifier. This illustrative fragment assumes $tokens has already been validated and $query is scoped:
$columns = ['name' => 'users.name', 'created_at' => 'users.created_at'];
foreach ($tokens as $token) {
    $descending = str_starts_with($token, '-');
    $alias = $descending ? substr($token, 1) : $token;
    abort_unless(isset($columns[$alias]), 422, 'Unsupported sort');
    $query->orderBy($columns[$alias], $descending ? 'desc' : 'asc');
}
$query->orderBy('users.id'); // deterministic tie-breaker
  1. Decide empty-sort/default-order behavior explicitly. Keep pagination bounded and preserve current response resources; do not serialize every model field. Refuse unsupported include/fields parameters rather than quietly returning a different authorization-sensitive shape.
  2. Keep the old implementation available while comparing representative requests. After parity for the declared slice, remove only the affected package calls and run composer why spatie/laravel-query-builder; other endpoints may still need it.

Verification

Use two tenants and asymmetric rows: tenant A has (name=Alex,status=active), (name=Alex,status=inactive), (name=A_100%,status=active); tenant B has a row that would otherwise sort first. Add matching timestamps to force a tie-breaker.

  • Exact active filtering excludes inactive, and every query excludes tenant B.
  • filter[name]=_100% matches the literal row, not all names; quote/backslash input never becomes SQL.
  • sort=-created_at,name follows left-to-right precedence; equal values remain stable across pages.
  • Unknown filter/sort names, sort=name desc;..., arrays where scalars are expected, unsupported includes, invalid enums, and oversized pages fail before the query runs. Check the existing API's expected error status rather than blindly adopting 422.
  • Empty, missing, 0, and boolean-like values retain the documented application behavior.

Run the endpoint's existing feature tests and new boundary cases with php artisan test --filter=UserIndex (replace with the real endpoint's test class). Compare actual ordered IDs, pagination metadata, status codes, and exposed fields against the package-backed endpoint. Record the comparison results before removing the package-backed path.