教你如何快速构建API查询

很多东西如果不是怕别人捡去,我们一定会扔掉。

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.

Basic usage

  • Filtering an API request: /users?filter[name]=John:

    1
    2
    3
    4
    5
    6
    7
    8
    use 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:

    1
    2
    3
    4
    $users = QueryBuilder::for(User::class)
    ->allowedIncludes('posts')
    ->get();
    // all `User`s with their `posts` loaded
  • Works together nicely with existing queries:

    1
    2
    3
    4
    5
    6
    $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:

    1
    2
    $users = QueryBuilder::for(User::class)->get();
    // all `User`s sorted by name

Installation

You can install the package via composer:

1
composer require spatie/laravel-query-builder

You can optionally publish the config file with:

1
php artisan vendor:publish --provider="Spatie\QueryBuilder\QueryBuilderServiceProvider" --tag="config"

This is the contents of the published config file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
return [

/*
* By default the package will use the `include`, `filter`, `sort` and `fields` query parameters.
*
* Here you can customize those names.
*/
'parameters' => [
'include' => 'include',

'filter' => 'filter',

'sort' => 'sort',

'fields' => 'fields',
],

];

https://laravel-news.com/laravel-query-builder
https://packagist.org/packages/spatie/laravel-query-builder
https://github.com/spatie/laravel-query-builder
https://spatie.be/en/opensource/laravel