You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
You can select only some fields to be included using the [`allowedFields` method on the query builder](https://spatie.be/docs/laravel-query-builder/v5/features/selecting-fields/).
172
+
You can select only some fields to be included using the [`allowedFields` method on the query builder](https://spatie.be/docs/laravel-query-builder/v6/features/selecting-fields/).
173
173
174
174
⚠️ `allowedFields` must be called before `allowedIncludes`. Otherwise the query builder wont know what fields to include for the requested includes and an exception will be thrown.
Selecting fields for included models works the same way. This is especially useful when you only need a couple of columns from an included relationship. Consider the following example:
43
43
44
44
```php
45
-
GET /posts?include=author&fields[author]=id,name
45
+
GET /posts?include=author&fields[authors]=id,name
46
46
47
47
QueryBuilder::for(Post::class)
48
-
->allowedFields('author.id', 'author.name')
48
+
->allowedFields('authors.id', 'authors.name')
49
49
->allowedIncludes('author');
50
50
51
51
// All posts will be fetched including _only_ the name of the author.
52
52
```
53
+
⚠️ **Note:** In `allowedFields`, you must always use the _snake case plural_ of your relation name. If you want to change this behavior, you can change the settings in the [configuration file](https://spatie.be/docs/laravel-query-builder/v6/installation-setup)
53
54
54
55
⚠️ Keep in mind that the fields query will completely override the `SELECT` part of the query. This means that you'll need to manually specify any columns required for Eloquent relationships to work, in the above example `author.id`. See issue [#175](https://github.com/spatie/laravel-query-builder/issues/175) as well.
0 commit comments