Laravel Query Builder is a package by Alex Vanderbist and the folks at Spatie, to quickly build Eloquent queries from API requests. This package makes creating complex API queries with Laravel incredibly simple. While you may have already heard of this package (or used it), I wanted to make sure everyone is aware of this one!
I highly recommend you take Query Builder for a spin and read through the README to learn what it’s capable of doing. It makes creating API filters and other query-related tasks so easy, you might feel like you’re cheating.
A few basic examples of what you can do include filtering an API request, including related models, incorporating it with existing queries, sorting an API request.
Filtering an API request: /users?filter[name]=John:12345678use Spatie\QueryBuilder\QueryBuilder;// ...$users = QueryBuilder::for(User::class)->allowedFilters('name')->get();// all `User`s that contain the string "John" in their name
Requesting relations from an API request: /users?include=posts:1234$users = QueryBuilder::for(User::class)->allowedIncludes('posts')->get();// all `User`s with their `posts` loaded
Works together nicely with existing queries:123456$query = User::where('active', true);$user = QueryBuilder::for($query)->allowedIncludes('posts', 'permissions')->where('score', '>', 42) // chain on any of Laravel's query builder methods->first();
Sorting an API request: /users?sort=name:12$users = QueryBuilder::for(User::class)->get();// all `User`s sorted by name
You can install the package via composer:
You can optionally publish the config file with:
This is the contents of the published config file: