Skip to content

Selecting fields ​

allowedFields() lists the columns a request may select. The fields[<key>] parameter takes a list of columns for the root model and for every included relation:

php
QueryBuilder::for(User::class)
    ->allowedFields('id', 'name', 'email', 'posts.id', 'posts.title')
    ->allowedIncludes('posts')
    ->get();
GET /users?fields[users]=name&fields[posts]=title&include=posts
sql
select "users"."name", "users"."id" from "users"
select "posts"."title", "posts"."user_id" from "posts" where "posts"."user_id" in (...)

A field not in the list throws InvalidFieldQuery. Without fields[...] all columns are selected.

Keys ​

The root is keyed by its table, fields[users]. An included relation is keyed by its name in snake case and plural: include=userOwner takes fields[user_owners]. The configuration can key relations by the name as written or by the table of the related model.

In allowedFields(), the columns of a relation are written with the relation in front: posts.title.

Keys of relations are added ​

The request above asks for users.name only, but the users are selected with id, and the posts with user_id: without them Eloquent could not match the posts to their users. Every relation type is covered, morphTo, pivots of belongsToMany and the through relations included. The added keys are ordinary attributes of the loaded models; hide them in your API resources if they must not be exposed.

With spatie the same request returns users whose posts are empty. See Introduction.

Order of calls ​

allowedFields() and allowedIncludes() may be called in any order: both are applied right before the query runs.

Fields of a relation in code ​

getRequestedFieldsForRelatedTable('posts') returns the columns the request asked for a relation, for code that loads it by hand.