This package allows you to filter, sort and include eloquent relations based on a request. The QueryBuilder
used in this package extends Laravel's default Eloquent builder. This means all your favorite methods and macros are still available. Query parameter names follow the JSON API specification as closely as possible.
Here's how we use the package ourselves in Mailcoach.
##Basic usage
##Filter a query based on a request: /users?filter[name]=John
:
use Spatie\QueryBuilder\QueryBuilder;
$users = QueryBuilder::for(User::class)
->allowedFilters('name')
->get();
Read more about filtering features like: partial filters, exact filters, scope filters, custom filters, ignored values, default filter values, ...
##Including relations based on a request: /users?include=posts
:
$users = QueryBuilder::for(User::class)
->allowedIncludes('posts')
->get();
Read more about include features like: including nested relationships, including relationship count, ...
$users = QueryBuilder::for(User::class)
->allowedSorts('id')
->get();
Read more about sorting features like: custom sorts, sort direction, ...
##Works together nicely with existing queries:
$query = User::where('active', true);
$userQuery = QueryBuilder::for($query)
->withTrashed()
->allowedIncludes('posts', 'permissions')
->where('score', '>', 42);
##Selecting fields for a query: /users?fields=id,email
$users = QueryBuilder::for(User::class)
->allowedFields(['id', 'email'])
->get();
Read more about selecting fields.
##Appending attributes to a query: /users?append=full_name
$users = QueryBuilder::for(User::class)
->allowedAppends('full_name')
->get()
->toJson();
Read more about appending attributes.
##We have badges!