Download the PHP package redsky-thirty/laravel-api-query-builder without Composer

On this page you can find all versions of the php package redsky-thirty/laravel-api-query-builder. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package laravel-api-query-builder

Laravel API Query Builder

A lightweight and composable query builder for Laravel APIs, inspired by GraphQL flexibility.
Select only the fields and relations you want. Filter, sort, paginate — cleanly.

Current version: 1.4.2
Last update: April 27, 2026


Table of contents


Features

Installation

Usage

Collection Mode

This mode is used to retrieve multiple results from the database. It can automatically decide between returning a full collection or a paginated response based on the presence of the per_page parameter.

Single Resource Mode

This mode allows you to build the query manually and return a single model instance (e.g., User::find(...)). Useful for retrieving one resource with relation and field selection logic applied.

Usage Without Executing a Query

You can initialize field and relation selection logic without executing any database queries using the prepareWithoutQuery() method. This is particularly useful when preparing resource responses or resolving metadata without needing to fetch actual records.

This method parses the requested fields from the URL and stores them in the internal FieldRegistry, allowing your resources to behave consistently with the API expectations — all without triggering any Eloquent or SQL operations.

Always Fields

Sometimes, certain fields are required internally even if the client hasn't explicitly requested them. For example, foreign keys used to link relationships.

To support this, the alwaysFields() method allows you to define fields that should always be included in the response, even if they are not present in the fields[...] parameters or in the defaultFields() fallback.

These fields will be automatically merged into the requested or default field set before the resource is rendered.

⚠️ Priority Rules

Sorting

The orderby parameter allows you to dynamically control the sort order of your API results.

Basic Usage

You can specify one or multiple fields to sort by.
By default, the sort order is ascending unless you prefix the field with a minus (-) for descending order.

Examples

Defining Allowed Sorts

To restrict which fields can be used for sorting, you can use the allowedSorts() method:

If a user tries to sort by a field not in the allowed list, the query builder will ignore it (or throw an exception if strict mode is enabled).

Default Sorts

You can define default sorts using the defaultSorts() method.
This will be applied automatically if no orderby parameter is provided.

This ensures that your API always returns predictable results even when no explicit sorting is requested.

Local Scopes

The query builder supports applying Eloquent local scopes directly from the URL via the scopes parameter.

Local scopes let you encapsulate commonly used query constraints in your models (e.g. scopeUnverified()unverified()).

Basic Usage

This will automatically call the method scopeUnverified() defined on the User model — equivalent to:

You can also pass multiple scopes separated by commas:

Note: Scopes are applied only to the root model, not to nested relations.

Whitelisting Allowed Scopes

To control which scopes can be applied from the URL, use the allowedScopes() method:

If a request includes a scope that is not allowed, it will either:

Syntax Variants

The following formats are all accepted and automatically normalized:

Input Invoked Scope
unverified scopeUnverified()
unverified() scopeUnverified()
scopeUnverified scopeUnverified()
scopeUnverified() scopeUnverified()

Wildcard Mode

To allow all local scopes to be accessible (not recommended in public APIs):

Custom Filters

Sometimes a filterable attribute does not map to a real database column — for example, a computed field, a cross-table search, or any condition that cannot be expressed as a simple where[column]=value.

The customFilters() method lets you register a closure for any such field. The closure receives the query builder, the raw value from the request, and the filter type ('where' or 'like'), giving you full control over how the condition is applied.

A common use case is a unified search parameter that matches across multiple columns or related tables in a single filter:

Notes

Resource example

DTO-backed Resources

By default, ApiResource expects an Eloquent model as its underlying resource. However, it is possible to back a resource with a DTO instead, while still benefiting from the full field-filtering logic provided by ApiResource.

To support this, the package provides the ApiDtoResource abstract class and the ApiResourceable contract.

When you own the DTO

If you have full control over the DTO class, implement the ApiResourceable interface on it. This requires two methods: getTable(), which returns the table or registry key used for field lookups, and getAttributes(), which returns the raw attributes as a key/value array.

If your DTO already exposes a toArray() method that matches the structure you want to expose, you can use it directly in getAttributes() instead of listing every property manually:

Then extend ApiDtoResource instead of ApiResource in your resource class:

Usage remains identical to a model-backed resource:

When you don't own the DTO

If the DTO comes from a third-party library and you cannot make it implement ApiResourceable, override resolveTable() and resolveAttributes() directly in the resource class. No adapter or intermediate class is needed.

If the DTO exposes a toArray() method that fits your needs, you can use it directly in resolveAttributes():

Otherwise, list the properties manually:

Usage is unchanged:

Accessing the DTO in data()

ApiDtoResource provides a dto() helper that returns $this->resource typed as ApiResourceable. This gives static analysis tools (PHPStan, Psalm) accurate type information, which $this->resource alone — declared as mixed in JsonResource — cannot provide.

If you prefer accessing DTO properties directly via $this->property without calling dto(), you can add a @mixin annotation on the resource class. This is purely an IDE hint and has no effect on static analysis tools:

Note: @mixin is recognized by PhpStorm and similar IDEs but is ignored by PHPStan and Psalm. If you rely on static analysis, prefer dto() for accurate type inference.

Field Resolution Without a Query (ApiFieldResolver)

When working with DTO-backed resources, there is no Eloquent model and no database query to execute. ApiQueryBuilder cannot be used in this context because it requires a model class. ApiFieldResolver fills this gap: it provides the same field resolution and FieldRegistry registration logic, without any query building or Eloquent dependency.

Basic Usage

Instantiate ApiFieldResolver in your controller before returning the resource. The prepare() call parses the fields[...] parameters from the request, filters them against allowedFields, and registers the result in FieldRegistry so that the resource can apply field filtering automatically.

With ?fields[users]=id,email, the response will only contain id and email.
Without any fields parameter, the resource falls back to its defaultFields().

alwaysFields Support

ApiFieldResolver supports alwaysFields() with the same semantics as ApiQueryBuilder: the specified fields are injected unconditionally into any non-wildcard selection.

Strict Mode

By default, strict mode is enabled: requesting a field not listed in allowedFields throws an InvalidFieldException. Pass false as the second argument to make() to silently drop disallowed fields instead.

Inspecting Resolved Fields

After calling prepare(), you can query the resolved field list directly on the resolver instance if needed.

Nested Relation Helpers

Sometimes you may want to include data in a Resource only if a nested relation has been loaded.
Laravel provides the whenLoaded() method but it only works with direct relations.

To solve this, the package includes the HasNestedWhenLoaded trait.

Usage

Behavior

Signature

Demo

This package includes a demo Laravel application for local testing and exploration.

🚀 Getting started

To launch the demo project:

Then open your browser at http://localhost:8000/api/users.

🔧 Customizing the Demo

The logic used to test the API query builder is defined inside:

You can modify or extend this file freely to experiment with:

This allows you to test the package without needing to copy files into a separate Laravel project.

Note: The demo/ folder is for local use only and should not be required in production.

Example URLs

1. Select default fields with relations

2. Select specific fields

3. Load relations and limit fields

4. Apply local scope

5. Filter with equals, OR and AND

6. Filter with operators

7. Search (LIKE)

8. Sort results

9. Pagination

10. "Single Resource Mode" and "Without Executing a Query"

All URL parameters related to field selection demonstrated above can also be used with single-resource endpoints like /api/users/{id} or /api/users/random.

This works especially well when using the prepareWithoutQuery() method, which allows parsing and validation of requested fields and relations without performing any database query. This ensures consistent response shaping even when loading a single resource outside of the query builder's automatic mode.

All URL examples provided above are fully replicable with the Single Resource usage (e.g. via /api/users/{id}).
This ensures a consistent API experience whether you're fetching a list of resources or a single one.

When using the prepareWithoutQuery() method (query-less mode), only field selection logic (i.e. the fields[...] parameters) is parsed and validated. This is useful for shaping responses or metadata without performing any database access — such as in the demo endpoints /api/users/random — but it does not apply filters, sorting, or relation loading.

Requirements

License

MIT © Redsky-Thirty


All versions of laravel-api-query-builder with dependencies

PHP Build Version
Package Version
Requires php Version ^8.4
illuminate/support Version ^12.0|^13.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package redsky-thirty/laravel-api-query-builder contains the following files

Loading the files please wait ...