Skip to content

Queries ​

FusionStack\Laravel\Query\ApiQuery turns a request's query string into an Eloquent query. A subclass lists what clients may ask for: related resources to include, fields, filters and sorts. Anything it does not list gets a 400 error that names the parameter and what is available. There are no silent fallbacks.

php
use App\Models\Order;
use FusionStack\Laravel\Query\ApiQuery;

/** @extends ApiQuery<Order> */
final class OrderQuery extends ApiQuery
{
    protected string $model = Order::class;

    protected array $includes = ['customer'];

    protected array $fields = [
        'orders' => ['reference', 'status', 'total', 'created_at', 'customer'],
        'customers' => ['name', 'email'],
    ];

    protected array $filters = [
        'status' => ['eq', 'in'],
        'total' => ['gte', 'lte'],
        'search' => SearchOrders::class,
    ];

    protected array $sorts = ['created_at', 'total'];

    protected string $defaultSort = '-created_at';
}

Type-hint it in a controller action, and Laravel creates it with the current request:

php
public function index(OrderQuery $query): AnonymousResourceCollection
{
    return OrderResource::collection($query->paginate());
}

public function show(OrderQuery $query, string $order): OrderResource
{
    return new OrderResource($query->find($order));
}

Name everything in the latest API version. Clients pinned to an older version use that version's names, and the version changes translate them, including in error messages.

Properties ​

PropertyTypeDefaultWhat it does
$modelclass-stringrequiredThe Eloquent model the endpoint lists.
$type?stringnullThe JSON:API type the endpoint returns. null derives it from the model, as JsonApiResource does: Order becomes orders. Set it when the resource names its own type, such as invoice-emails.
$includeslist<string>[]Relationship paths clients may include, such as customer or customer.orders. Listing a nested path allows its parents too.
$fieldsarray<string, list<string>>[]The fields clients may select, by type. A type that is not listed cannot be used in fields[...].
$filtersarray<string, list<string>|class-string<Filter>>[]Each filter, with the operators it allows or a Filter class.
$sortslist<string>[]The columns clients may sort by.
$defaultSortstring''The sort when the request has none, such as -created_at. Empty sorts by primary key.
$pagination'cursor'|'offset''cursor'How results are paged. See pagination.
$withTotalboolfalseWith offset pagination, also count every result, for meta.page.total and a last link. It costs one more query.

Includes ​

?include=customer,customer.orders adds related resources to the document's included member, each once however many resources refer to it. JsonApiResource loads each included relationship with one query, so includes never cause N+1 queries.

RequestResult
A path in $includes, or a parent of oneIncluded
Any other path400 invalid_include
A path nested more deeply than api.query.max_include_depth (3)400 invalid_include

Sparse fieldsets ​

?fields[orders]=reference,total&fields[customers]=name limits each type's attributes and relationships to those named. A type that is not in $fields, or a field that is not in its list, is a 400 invalid_fieldset. Without fields, the resource returns everything it lists.

Filters ​

?filter[status]=paid compares with eq. ?filter[total][gte]=5000 names the operator. Several filters, and several operators on one filter, all apply.

OperatorSQLExample
eq=filter[status]=paid
ne!=filter[status][ne]=cancelled
gt>filter[total][gt]=0
gte>=filter[created_at][gte]=2027-01-01
lt<filter[total][lt]=1000
lte<=filter[total][lte]=1000
inINfilter[status][in]=paid,shipped

A column filter compares the column of the same name. An unknown filter, or an operator the filter does not list, is a 400 invalid_filter. Values are always strings, compared as the database compares them.

Custom filters ​

For anything a column comparison cannot express, such as a search across columns or a condition on a relationship, implement FusionStack\Laravel\Query\Filter and list the class:

php
use FusionStack\Laravel\Query\Filter;
use Illuminate\Database\Eloquent\Builder;

final class SearchOrders implements Filter
{
    /** The operators clients may use: here only filter[search]=… */
    public function operators(): array
    {
        return ['eq'];
    }

    public function apply(Builder $query, string $operator, string $value): void
    {
        $query->where(fn (Builder $query) => $query
            ->where('reference', 'like', "%{$value}%")
            ->orWhereRelation('customer', 'name', 'like', "%{$value}%"));
    }
}

Filters are created by the container, so their constructors can take dependencies. Describe each filter for the API reference with #[Describe] on the query class.

Sorts ​

?sort=-total,created_at sorts by each column in turn. A - sorts in descending order. A column that is not in $sorts is a 400 invalid_sort. The primary key is always added last, so the order is stable and cursors work.

Pagination ​

Every list is paginated, with page[size] from 1 to api.query.max_page_size (100), defaulting to api.query.page_size (25). A size outside that range is a 400 invalid_page.

$paginationParameterslinksmeta.page
cursor (default)page[size], page[after], page[before]first, prev, nextsize
offsetpage[size], page[number]first, prev, next, and last with $withTotalnumber, size, and total with $withTotal

Cursor pagination stays fast on large tables and does not skip or repeat rows when rows are added. Use offset pagination when clients need to jump to a page number. Clients should follow the links rather than build cursors: a cursor from a request with a different sort is a 400 invalid_page. Links keep the request's other parameters.

Methods ​

scope() ​

php
protected function scope(Builder $query, ?ApiClient $client): void

Override it to limit what the caller may see, such as their own team's records. It runs before filters, sorts and pagination, and in find(), so no query parameter reaches past it. $client is null for a guest.

php
protected function scope(Builder $query, ?ApiClient $client): void
{
    $query->where('team_id', $this->request->user()?->team_id);
}

$this->request is the current request, for route parameters such as $this->request->route('order').

paginate() ​

Returns a page of the scoped, filtered and sorted results, as a cursor or offset paginator. Pass it to Resource::collection(), which adds the JSON:API links and meta.

find() ​

php
public function find(int|string $id): Model

Returns one record within scope(), or throws, which is rendered as 404 not_found. It also checks include and fields, so GET /v1/orders/1?include=customer works as it does on the list.

builder() ​

Returns the scoped, filtered and sorted Eloquent builder without paginating, for aggregates or exports.

describe() ​

Returns what clients may ask for: the model, type, includes, fields, filters with their operators, sorts, default sort and pagination. The OpenAPI generator reads it to document the query parameters, so you rarely call it yourself.

Errors ​

CodeWhen
invalid_includeAn include path that is not allowed, or nested too deeply.
invalid_fieldsetA type or field that is not in $fields.
invalid_filterAn unknown filter, an operator it does not allow, or a value that is not a string.
invalid_sortA column that is not in $sorts.
invalid_pageAn unknown page[...] parameter, a size out of range, or a cursor that is not valid for this sort.

Each error's source.parameter names the parameter, such as filter[status][gt], and its detail lists what is available.

Released under the MIT License.