Skip to content

4. Filtering, sorting and includes ​

A shop's staff want the paid orders, the biggest orders first, or the orders with the name of the team that placed each one. In this step you let clients ask for those, with the query string, and see what happens when they ask for something you did not allow.

Some orders to work with ​

Made-up data makes results hard to check, so add a seeder that creates two teams with orders you know. A seeder fills the database with data, for development:

php
<?php

namespace Database\Seeders;

use App\Models\Order;
use App\Models\Team;
use Illuminate\Database\Seeder;

/** Two teams with orders whose values are known, to try filters and sorts on. */
final class OrderSeeder extends Seeder
{
    public function run(): void
    {
        $acme = Team::query()->create(['name' => 'Acme Ltd', 'plan' => 'pro']);
        $globex = Team::query()->create(['name' => 'Globex', 'plan' => 'enterprise']);

        foreach ([
            [$acme, 'paid', 4999, 'GBP', 1],
            [$acme, 'shipped', 12000, 'GBP', 2],
            [$acme, 'pending', 1500, 'GBP', 5],
            [$globex, 'cancelled', 800, 'USD', 3],
            [$globex, 'paid', 30500, 'USD', 4],
            [$globex, 'shipped', 7250, 'USD', 6],
        ] as [$team, $status, $total, $currency, $daysAgo]) {
            $order = new Order(['team_id' => $team->id, 'status' => $status, 'total_cents' => $total, 'currency' => $currency]);
            $order->created_at = now()->subDays($daysAgo);
            $order->save();
        }
    }
}

Run it:

sh
php artisan db:seed --class=OrderSeeder
text
INFO Seeding database.

Also add it to the main seeder, so the orders come back whenever you rebuild the database with php artisan migrate:fresh --seed:

diff
         Team::factory(12)->create();
+
+        $this->call(OrderSeeder::class);
     }

Allow filters, sorts and includes ​

Every collection endpoint in Fusion Stack starts closed: a client can only filter, sort or include what its query class allows. Update the query:

php
<?php

namespace App\Http\Queries;

use App\Models\Order;
use FusionStack\Laravel\OpenApi\Describe;
use FusionStack\Laravel\Query\ApiQuery;

/** @extends ApiQuery<Order> */
#[Describe('status', 'pending, paid, shipped or cancelled.')]
#[Describe('total_cents', 'The total in the smallest unit of the currency, such as 5000 for 50.00.')]
#[Describe('currency', 'EUR, GBP or USD.')]
final class OrderQuery extends ApiQuery
{
    protected string $model = Order::class;

    protected array $includes = ['team'];

    protected array $fields = [
        'orders' => ['status', 'total_cents', 'currency', 'created_at', 'team'],
        'teams' => ['name', 'plan', 'created_at', 'updated_at'],
    ];

    protected array $filters = [
        'status' => ['eq', 'in'],
        'total_cents' => ['gte', 'lte'],
        'currency' => ['eq'],
    ];

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

    protected string $defaultSort = '-created_at';
}
PropertyWhat it allows
$includesRelated resources a client may ask for with ?include=, in the same response.
$fieldsThe fields of each type a client may pick with ?fields[type]=.
$filtersEach attribute a client may filter by, with the operators it may use: eq (the default), in, gte (at least), lte (at most) and others.
$sortsThe attributes a client may sort by with ?sort=. A - in front sorts in descending order.

#[Describe] explains each filter in the API reference. The glossary explains the terms.

Filter ​

The paid orders, with only the attributes you need:

sh
curl -g "localhost:8000/v1/orders?filter[status]=paid&fields[orders]=status,total_cents,currency"
json
{
  "data": [
    { "id": "2", "type": "orders", "attributes": { "status": "paid", "total_cents": 4999, "currency": "GBP" } },
    { "id": "6", "type": "orders", "attributes": { "status": "paid", "total_cents": 30500, "currency": "USD" } }
  ],
  "links": { "first": "http://localhost:8000/v1/orders?…", "prev": null, "next": null },
  "meta": { "page": { "size": 25 } }
}

fields[orders] is a sparse fieldset: the response has only the attributes you asked for, which keeps it small. Without it, you get them all.

Combine filters, and sort ​

Paid or shipped orders of at least 50.00, the biggest first:

sh
curl -g "localhost:8000/v1/orders?filter[status][in]=paid,shipped&filter[total_cents][gte]=5000&sort=-total_cents&fields[orders]=status,total_cents"
json
{
  "data": [
    { "id": "6", "type": "orders", "attributes": { "status": "paid", "total_cents": 30500 } },
    { "id": "3", "type": "orders", "attributes": { "status": "shipped", "total_cents": 12000 } },
    { "id": "7", "type": "orders", "attributes": { "status": "shipped", "total_cents": 7250 } }
  ],
  "links": { "first": "http://localhost:8000/v1/orders?…", "prev": null, "next": null },
  "meta": { "page": { "size": 25 } }
}

Filters on different attributes all apply. Order 2, for 49.99, is paid but too small.

The orders in dollars, with the name of each order's team:

sh
curl -g "localhost:8000/v1/orders?filter[currency]=USD&include=team&fields[orders]=total_cents,team&fields[teams]=name"
json
{
  "data": [
    {
      "id": "5",
      "type": "orders",
      "attributes": { "total_cents": 800 },
      "relationships": { "team": { "data": { "id": "14", "type": "teams" } } }
    },
    {
      "id": "6",
      "type": "orders",
      "attributes": { "total_cents": 30500 },
      "relationships": { "team": { "data": { "id": "14", "type": "teams" } } }
    },
    {
      "id": "7",
      "type": "orders",
      "attributes": { "total_cents": 7250 },
      "relationships": { "team": { "data": { "id": "14", "type": "teams" } } }
    }
  ],
  "links": { "first": "http://localhost:8000/v1/orders?…", "prev": null, "next": null },
  "meta": { "page": { "size": 25 } },
  "included": [{ "id": "14", "type": "teams", "attributes": { "name": "Globex" } }]
}

Each order points to its team in relationships, and the team itself is in included, once, however many orders share it. A client gets everything it needs to show the list in one request, rather than one more request per order. The database is asked once for the orders and once for their teams, however many there are.

Ask for something not allowed ​

Sort by status, which the query does not allow:

sh
curl -g "localhost:8000/v1/orders?sort=status"
json
{
  "errors": [
    {
      "status": "400",
      "code": "invalid_sort",
      "title": "Invalid sort",
      "detail": "Results cannot be sorted by [status]. Available: created_at, total_cents.",
      "source": { "parameter": "sort" },
      "meta": { "request_id": "req_01m8rf3bq5a2kz7v9x4c6d8e1f" }
    }
  ]
}

The API refuses, rather than ignoring the parameter and returning results in another order: the client would show them as sorted without anyone noticing. The error lists what is available. Unknown filters, operators and includes are refused the same way. Every query a client can run is one you planned for, and can index the database for.

The filter is ignored, or a 400 says the filter is unknown

Check the brackets: filter[status][in]=paid,shipped, with the attribute first and then the operator. Without -g, curl reads the brackets itself, as in step 2.

The IDs or teams in the output differ from yours

The seeder ran more than once, which adds the teams and orders again. To start again, run php artisan migrate:fresh --seed: it empties the database and runs every seeder. Then create an API key again, as in step 2, as the old one is gone.

Test it ​

Add tests for a combined filter and sort, an include and a refused request, to tests/Feature/OrderTest.php:

php
<?php

use App\Models\Order;
use App\Models\Team;

it('places a pending order for a team', function (): void {
    $team = Team::factory()->create();

    $this->api()->postJson('/v1/orders', ['data' => [
        'type' => 'orders',
        'attributes' => ['total_cents' => 2500, 'currency' => 'GBP'],
        'relationships' => ['team' => ['data' => ['type' => 'teams', 'id' => (string) $team->id]]],
    ]])
        ->assertCreated()
        ->assertJsonApiResource('orders')
        ->assertJsonPath('data.attributes.status', 'pending');

    expect(Order::query()->sole()->team_id)->toBe($team->id);
});

it('rejects an order in a currency it does not take', function (): void {
    $this->api()->postJson('/v1/orders', ['data' => [
        'type' => 'orders',
        'attributes' => ['total_cents' => 2500, 'currency' => 'JPY'],
        'relationships' => ['team' => ['data' => ['type' => 'teams', 'id' => (string) Team::factory()->create()->id]]],
    ]])
        ->assertApiError('validation_failed', 422)
        ->assertJsonPath('errors.0.source.pointer', '/data/attributes/currency');

    expect(Order::query()->count())->toBe(0);
});

it('lists orders, newest first', function (): void {
    $old = Order::factory()->create(['created_at' => now()->subDay()]);
    $new = Order::factory()->create();

    $this->api()->getJson('/v1/orders')
        ->assertJsonApiCollection('orders', 2)
        ->assertJsonPath('data.0.id', (string) $new->id)
        ->assertJsonPath('data.1.id', (string) $old->id);
});

it('filters by status and total, and sorts by total', function (): void {
    Order::factory()->createMany([
        ['status' => 'paid', 'total_cents' => 9000],
        ['status' => 'shipped', 'total_cents' => 6000],
        ['status' => 'paid', 'total_cents' => 4000],
        ['status' => 'pending', 'total_cents' => 8000],
    ]);

    $this->api()->getJson('/v1/orders?filter[status][in]=paid,shipped&filter[total_cents][gte]=5000&sort=total_cents')
        ->assertJsonApiCollection('orders', 2)
        ->assertJsonPath('data.0.attributes.total_cents', 6000)
        ->assertJsonPath('data.1.attributes.total_cents', 9000);
});

it('includes the team, and rejects what the query does not allow', function (): void {
    Order::factory()->for(Team::factory()->create(['name' => 'Acme Ltd']))->create();

    $this->api()->getJson('/v1/orders?include=team')
        ->assertJsonPath('data.0.relationships.team.data.type', 'teams')
        ->assertJsonPath('included.0.attributes.name', 'Acme Ltd');

    $this->api()->getJson('/v1/orders?sort=status')->assertApiError('invalid_sort', 400);
    $this->api()->getJson('/v1/orders?filter[currency][in]=GBP,USD')->assertApiError('invalid_filter', 400);
});
sh
composer check
text
Tests: … passed (… assertions)

Next: authentication and scopes.

Released under the MIT License.