Loading... # Eloquent: Collections ## [Introduction](https://laravel.com/docs/8.x/eloquent-collections#introduction) All Eloquent methods that return more than one model result will return instances of the `Illuminate\Database\Eloquent\Collection` class, including results retrieved via the `get` method or accessed via a relationship. The Eloquent collection object extends Laravel's [base collection](https://laravel.com/docs/8.x/collections), so it naturally inherits dozens of methods used to fluently work with the underlying array of Eloquent models. Be sure to review the Laravel collection documentation to learn all about these helpful methods! All collections also serve as iterators, allowing you to loop over them as if they were simple PHP arrays: ```php use App\Models\User; $users = User::where('active', 1)->get(); foreach ($users as $user) { echo $user->name; } ``` However, as previously mentioned, collections are much more powerful than arrays and expose a variety of map / reduce operations that may be chained using an intuitive interface. For example, we may remove all inactive models and then gather the first name for each remaining user: ```php $names = User::all()->reject(function ($user) { return $user->active === false; })->map(function ($user) { return $user->name; }); ``` #### [Eloquent Collection Conversion](https://laravel.com/docs/8.x/eloquent-collections#eloquent-collection-conversion) While most Eloquent collection methods return a new instance of an Eloquent collection, the `collapse`, `flatten`, `flip`, `keys`, `pluck`, and `zip` methods return a [base collection](https://laravel.com/docs/8.x/collections) instance. Likewise, if a `map` operation returns a collection that does not contain any Eloquent models, it will be converted to a base collection instance. ## [Available Methods](https://laravel.com/docs/8.x/eloquent-collections#available-methods) All Eloquent collections extend the base [Laravel collection](https://laravel.com/docs/8.x/collections#available-methods) object; therefore, they inherit all of the powerful methods provided by the base collection class. In addition, the `Illuminate\Database\Eloquent\Collection` class provides a superset of methods to aid with managing your model collections. Most methods return `Illuminate\Database\Eloquent\Collection` instances; however, some methods, like `modelKeys`, return an `Illuminate\Support\Collection` instance. [contains](https://laravel.com/docs/8.x/eloquent-collections#method-contains)[diff](https://laravel.com/docs/8.x/eloquent-collections#method-diff)[except](https://laravel.com/docs/8.x/eloquent-collections#method-except)[find](https://laravel.com/docs/8.x/eloquent-collections#method-find)[fresh](https://laravel.com/docs/8.x/eloquent-collections#method-fresh)[intersect](https://laravel.com/docs/8.x/eloquent-collections#method-intersect)[load](https://laravel.com/docs/8.x/eloquent-collections#method-load)[loadMissing](https://laravel.com/docs/8.x/eloquent-collections#method-loadMissing)[modelKeys](https://laravel.com/docs/8.x/eloquent-collections#method-modelKeys)[makeVisible](https://laravel.com/docs/8.x/eloquent-collections#method-makeVisible)[makeHidden](https://laravel.com/docs/8.x/eloquent-collections#method-makeHidden)[only](https://laravel.com/docs/8.x/eloquent-collections#method-only)[toQuery](https://laravel.com/docs/8.x/eloquent-collections#method-toquery)[unique](https://laravel.com/docs/8.x/eloquent-collections#method-unique) #### [`contains($key, $operator = null, $value = null)`](https://laravel.com/docs/8.x/eloquent-collections#method-contains) The `contains` method may be used to determine if a given model instance is contained by the collection. This method accepts a primary key or a model instance: ``` $users->contains(1); $users->contains(User::find(1)); ``` #### [`diff($items)`](https://laravel.com/docs/8.x/eloquent-collections#method-diff) The `diff` method returns all of the models that are not present in the given collection: ```php use App\Models\User; $users = $users->diff(User::whereIn('id', [1, 2, 3])->get()); ``` #### [`except($keys)`](https://laravel.com/docs/8.x/eloquent-collections#method-except) The `except` method returns all of the models that do not have the given primary keys: ``` $users = $users->except([1, 2, 3]); ``` #### [`find($key)`](https://laravel.com/docs/8.x/eloquent-collections#method-find) The `find` method returns the model that has a primary key matching the given key. If `$key` is a model instance, `find` will attempt to return a model matching the primary key. If `$key` is an array of keys, `find` will return all models which have a primary key in the given array: ```php $users = User::all(); $user = $users->find(1); ``` #### [`fresh($with = [\])`](https://laravel.com/docs/8.x/eloquent-collections#method-fresh) The `fresh` method retrieves a fresh instance of each model in the collection from the database. In addition, any specified relationships will be eager loaded: ```php $users = $users->fresh(); $users = $users->fresh('comments'); ``` #### [`intersect($items)`](https://laravel.com/docs/8.x/eloquent-collections#method-intersect) The `intersect` method returns all of the models that are also present in the given collection: ```php use App\Models\User; $users = $users->intersect(User::whereIn('id', [1, 2, 3])->get()); ``` #### [`load($relations)`](https://laravel.com/docs/8.x/eloquent-collections#method-load) The `load` method eager loads the given relationships for all models in the collection: ```php $users->load(['comments', 'posts']); $users->load('comments.author'); ``` #### [`loadMissing($relations)`](https://laravel.com/docs/8.x/eloquent-collections#method-loadMissing) The `loadMissing` method eager loads the given relationships for all models in the collection if the relationships are not already loaded: ```php $users->loadMissing(['comments', 'posts']); $users->loadMissing('comments.author'); ``` #### [`modelKeys()`](https://laravel.com/docs/8.x/eloquent-collections#method-modelKeys) The `modelKeys` method returns the primary keys for all models in the collection: ```php $users->modelKeys(); // [1, 2, 3, 4, 5] ``` #### [`makeVisible($attributes)`](https://laravel.com/docs/8.x/eloquent-collections#method-makeVisible) The `makeVisible` method [makes attributes visible](https://laravel.com/docs/8.x/eloquent-serialization#hiding-attributes-from-json) that are typically "hidden" on each model in the collection: ```php $users = $users->makeVisible(['address', 'phone_number']); ``` #### [`makeHidden($attributes)`](https://laravel.com/docs/8.x/eloquent-collections#method-makeHidden) The `makeHidden` method [hides attributes](https://laravel.com/docs/8.x/eloquent-serialization#hiding-attributes-from-json) that are typically "visible" on each model in the collection: ```php $users = $users->makeHidden(['address', 'phone_number']); ``` #### [`only($keys)`](https://laravel.com/docs/8.x/eloquent-collections#method-only) The `only` method returns all of the models that have the given primary keys: ```php $users = $users->only([1, 2, 3]); ``` #### [`toQuery()`](https://laravel.com/docs/8.x/eloquent-collections#method-toquery) The `toQuery` method returns an Eloquent query builder instance containing a `whereIn` constraint on the collection model's primary keys: ```php use App\Models\User; $users = User::where('status', 'VIP')->get(); $users->toQuery()->update([ 'status' => 'Administrator', ]); ``` #### [`unique($key = null, $strict = false)`](https://laravel.com/docs/8.x/eloquent-collections#method-unique) The `unique` method returns all of the unique models in the collection. Any models of the same type with the same primary key as another model in the collection are removed: ```php $users = $users->unique(); ``` ## [Custom Collections](https://laravel.com/docs/8.x/eloquent-collections#custom-collections) If you would like to use a custom `Collection` object when interacting with a given model, you may define a `newCollection` method on your model: ```php <?php namespace App\Models; use App\Support\UserCollection; use Illuminate\Database\Eloquent\Model; class User extends Model { /** * Create a new Eloquent Collection instance. * * @param array $models * @return \Illuminate\Database\Eloquent\Collection */ public function newCollection(array $models = []) { return new UserCollection($models); } } ``` Once you have defined a `newCollection` method, you will receive an instance of your custom collection anytime Eloquent would normally return an `Illuminate\Database\Eloquent\Collection` instance. If you would like to use a custom collection for every model in your application, you should define the `newCollection` method on a base model class that is extended by all of your application's models. Last modification:May 24, 2023 © Allow specification reprint Like 如果觉得我的文章对你有用,请随意赞赏