Including relationships | laravel-query-builder | Spatie

 SPATIE

  Laravel Query Builder
========================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-query-builder](https://spatie.be/docs/laravel-query-builder/v2)  Features  Including relationships

 Version   v7   v6   v5   v4   v3   v2

 Other versions for crawler [v7](https://spatie.be/docs/laravel-query-builder/v7) [v6](https://spatie.be/docs/laravel-query-builder/v6) [v5](https://spatie.be/docs/laravel-query-builder/v5) [v4](https://spatie.be/docs/laravel-query-builder/v4) [v3](https://spatie.be/docs/laravel-query-builder/v3) [v2](https://spatie.be/docs/laravel-query-builder/v2)

  Including relationships
- [ Introduction ](https://spatie.be/docs/laravel-query-builder/v2/introduction)
- [ Requirements ](https://spatie.be/docs/laravel-query-builder/v2/requirements)
- [ About us ](https://spatie.be/docs/laravel-query-builder/v2/about-us)
- [ Installation &amp; setup ](https://spatie.be/docs/laravel-query-builder/v2/installation-setup)
- [ Support us ](https://spatie.be/docs/laravel-query-builder/v2/support-us)
- [ Questions and issues ](https://spatie.be/docs/laravel-query-builder/v2/questions-issues)
- [ Changelog ](https://spatie.be/docs/laravel-query-builder/v2/changelog)

Features
--------

- [ Filtering ](https://spatie.be/docs/laravel-query-builder/v2/features/filtering)
- [ Sorting ](https://spatie.be/docs/laravel-query-builder/v2/features/sorting)
- [ Including relationships ](https://spatie.be/docs/laravel-query-builder/v2/features/including-relationships)
- [ Selecting fields ](https://spatie.be/docs/laravel-query-builder/v2/features/selecting-fields)
- [ Appending attributes ](https://spatie.be/docs/laravel-query-builder/v2/features/appending-attributes)

Advanced usage
--------------

- [ Extending query builder ](https://spatie.be/docs/laravel-query-builder/v2/advanced-usage/extending-query-builder)
- [ Pagination ](https://spatie.be/docs/laravel-query-builder/v2/advanced-usage/pagination)
- [ Front-end implementation ](https://spatie.be/docs/laravel-query-builder/v2/advanced-usage/front-end-implementation)
- [ Multi value delimiter ](https://spatie.be/docs/laravel-query-builder/v2/advanced-usage/multi-value-delimiter)

      You are viewing the documentation for **an older version** of this package. You can check the version you are using with the following command:

 `                                    composer show spatie/laravel-query-builder                                                                                                                                                                                                                                    `

Including relationships
=======================

###  On this page

1. [ Basic usage ](#content-basic-usage)
2. [ Disallowed includes ](#content-disallowed-includes)
3. [ Nested relationships ](#content-nested-relationships)
4. [ Including related model count ](#content-including-related-model-count)
5. [ Selecting included fields ](#content-selecting-included-fields)
6. [ Include casing ](#content-include-casing)
7. [ Eloquent API resources ](#content-eloquent-api-resources)

The `include` query parameter will load any Eloquent relation or relation count on the resulting models. All includes must be explicitly allowed using `allowedIncludes()`. This method takes an array of relationship names or `AllowedInclude` instances.

Basic usage
-----------------------------------------------------------------------------------------

```
// GET /users?include=posts

$users = QueryBuilder::for(User::class)
    ->allowedIncludes(['posts'])
    ->get();

// $users will have all their their `posts()` related models loaded
```

You can load multiple relationships by separating them with a comma:

```
// GET /users?include=posts,permissions
$users = QueryBuilder::for(User::class)
    ->allowedIncludes(['posts', 'permissions'])
    ->get();

// $users will contain all users with their posts and permissions loaded
```

Disallowed includes
-----------------------------------------------------------------------------------------------------------------

When trying to include relationships that have not been allowed using `allowedIncludes()` an `InvalidIncludeQuery` exception will be thrown. Its exception message contains the allowed includes for reference.

Nested relationships
--------------------------------------------------------------------------------------------------------------------

You can load nested relationships using the dot `.` notation:

```
// GET /users?include=posts.comments,permissions

$users = QueryBuilder::for(User::class)
    ->allowedIncludes(['posts.comments', 'permissions'])
    ->get();

// $users will contain all users with their posts, comments on their posts and permissions loaded
```

Including related model count
-----------------------------------------------------------------------------------------------------------------------------------------------

Every allowed include will automatically allow requesting its related model count using a `Count` suffix. On top of that it's also possible to specifically allow requesting and querying the related model count (and not include the entire relationship).

Under the hood this uses Laravel's `withCount method`. [Read more about the `withCount` method here](https://laravel.com/docs/master/eloquent-relationships#counting-related-models).

```
// GET /users?include=postsCount,friendsCount

$users = QueryBuilder::for(User::class)
    ->allowedIncludes([
        'posts', // allows including `posts` or `postsCount`
        AllowedInclude::count('friendsCount'), // only allows include the number of `friends()` related models
    ]);
// every user in $users will contain a `posts_count` and `friends_count` property
```

Selecting included fields
-----------------------------------------------------------------------------------------------------------------------------------

You can select only some fields to be included using the [`allowedFields` method on the query builder](https://docs.spatie.be/laravel-query-builder/v2/features/selecting-fields/).

⚠️ `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.

Include casing
--------------------------------------------------------------------------------------------------

Relation/include names will be converted to camelCase when looking for the corresponding relationship on the model. This means `/users?include=blog-posts` and `/users?include=blogPosts` will both try to load the `blogPosts()` relationship.

Eloquent API resources
--------------------------------------------------------------------------------------------------------------------------

Once the relationships are included, we'd recommend including them in your response by using [Eloquent API resources and conditional relationships](https://laravel.com/docs/master/eloquent-resources#conditional-relationships).

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
