> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Eloquent collections

> Learn the dedicated methods of Illuminate\Database\Eloquent\Collection and how to build custom collections.

## Introduction

When you retrieve multiple models with Eloquent, the results are returned as an `Illuminate\Database\Eloquent\Collection`.\
Because it extends `Illuminate\Support\Collection`, all the base collection methods are available.

```mermaid theme={null}
classDiagram
    class "Illuminate\\Support\\Collection" as SupportCollection
    class "Illuminate\\Database\\Eloquent\\Collection" as EloquentCollection
    SupportCollection <|-- EloquentCollection
```

```php theme={null}
use App\Models\User;

$users = User::where('active', true)->get();

foreach ($users as $user) {
    echo $user->name;
}
```

It's easier to understand how Eloquent collections extend the base if you first familiarize yourself with [Collections](/en/collections) and [Eloquent basics](/en/eloquent).

## Available methods

`Eloquent\Collection` inherits every method from the base collection and adds more methods for working with models.

### `append` / `withoutAppends` / `setAppends`

Manipulate serialization appends across the entire collection.

```php theme={null}
$users->append('team');
$users->append(['team', 'is_admin']);

$users = $users->withoutAppends();
$users = $users->setAppends(['is_admin']);
```

### `contains` / `diff` / `except` / `intersect` / `only`

Perform containment checks, differences, intersections, exclusion, and selection based on model instances or primary keys.

```php theme={null}
use App\Models\User;

$users->contains(1);
$users->contains(User::find(1));

$subset = User::whereIn('id', [1, 2, 3])->get();

$users->diff($subset);
$users->intersect($subset);

$users->except([1, 2, 3]);
$users->only([1, 2, 3]);
```

### `find` / `findOrFail`

Look up a model by primary key from an already-retrieved collection.

```php theme={null}
$users = User::all();

$user = $users->find(1);
$user = $users->findOrFail(1);
```

### `fresh`

Refresh each model in the collection with the latest state from the database.

```php theme={null}
$users = $users->fresh();
$users = $users->fresh('comments');
```

### `load` / `loadMissing`

Eager-load relationships onto an already-retrieved collection after the fact.

```php theme={null}
$users->load(['comments', 'posts']);
$users->load('comments.author');
$users->load(['comments', 'posts' => fn ($query) => $query->where('active', 1)]);

$users->loadMissing(['comments', 'posts']);
$users->loadMissing('comments.author');
$users->loadMissing(['comments', 'posts' => fn ($query) => $query->where('active', 1)]);
```

### `modelKeys`

Get the list of primary keys of the models in the collection.

```php theme={null}
$users->modelKeys();
// [1, 2, 3, ...]
```

### `makeVisible` / `makeHidden` / `mergeVisible` / `mergeHidden` / `setVisible` / `setHidden`

Adjust which attributes are visible or hidden for serialization at the collection level.

```php theme={null}
$users = $users->makeVisible(['address', 'phone_number']);
$users = $users->makeHidden(['address', 'phone_number']);

$users = $users->mergeVisible(['middle_name']);
$users = $users->mergeHidden(['last_login_at']);

$users = $users->setVisible(['id', 'name']);
$users = $users->setHidden(['email', 'password', 'remember_token']);
```

### `partition`

Split into two `Eloquent\Collection` instances by condition, wrapped in an outer `Illuminate\Support\Collection`.

```php theme={null}
$partition = $users->partition(fn ($user) => $user->age > 18);

dump($partition::class);    // Illuminate\Support\Collection
dump($partition[0]::class); // Illuminate\Database\Eloquent\Collection
dump($partition[1]::class); // Illuminate\Database\Eloquent\Collection
```

### `toQuery`

Build a `whereIn` query against the primary keys of the retrieved models so you can update or delete them all at once.

```php theme={null}
use App\Models\User;

// First, retrieve users matching the condition
$vipUsers = User::where('status', 'VIP')->get();

// Update only the models in the collection in a single query
$vipUsers->toQuery()->update([
    'status' => 'Administrator',
]);
```

<Tip>
  Instead of looping over individual `save()` calls, converting to a batch query with `toQuery()` gives you both performance and readability in production.
</Tip>

### `unique`

Remove duplicate models that have the same primary key.

```php theme={null}
$users = $users->unique();
```

## Converting an Eloquent collection to a base collection

`collapse`, `flatten`, `flip`, `keys`, `pluck`, and `zip` return an `Illuminate\Support\Collection`.\
Also, if the result of `map` does not contain Eloquent models, it's converted to a base collection.

## Custom collections

If you want to use a model-specific collection class, the clearest option is to use the `#[CollectedBy]` attribute.

### `#[CollectedBy]` attribute (recommended)

```php theme={null}
<?php

namespace App\Models;

use App\Support\UserCollection;
use Illuminate\Database\Eloquent\Attributes\CollectedBy;
use Illuminate\Database\Eloquent\Model;

#[CollectedBy(UserCollection::class)]
class User extends Model
{
    // ...
}
```

### `newCollection()` method (alternative)

```php theme={null}
<?php

namespace App\Models;

use App\Support\UserCollection;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function newCollection(array $models = []): Collection
    {
        $collection = new UserCollection($models);

        if (Model::isAutomaticallyEagerLoadingRelationships()) {
            $collection->withRelationshipAutoloading();
        }

        return $collection;
    }
}
```

When you define `newCollection()` or `#[CollectedBy]`, your custom collection is returned wherever an `Eloquent\Collection` would normally be returned.\
If you want to apply this to all models, define `newCollection()` on a common base model.

## Related pages

<Card title="Collections" icon="list" href="/en/collections">
  Review the basics of `Illuminate\\Support\\Collection` first.
</Card>

<Card title="Eloquent basics" icon="database" href="/en/eloquent">
  Understand the basics of models and queries before using Eloquent collections.
</Card>


## Related topics

- [Collections](/en/collections.md)
- [Collection Deep Dive](/en/advanced/collection-deep-dive.md)
- [Eloquent API resources](/en/eloquent-resources.md)
- [Higher Order Messages](/en/advanced/higher-order-messages.md)
- [Laravel AI SDK](/en/ai-sdk.md)
