Data format returned by Eloquent query: collection


brief introduction

Eloquent returns a result set containing multiple records Illuminate\Database\Eloquent\Collection Instances of objects, including through get Method or the result obtained by accessing the association relationship. The Eloquent collection object inherits from the Collection base class Therefore, it naturally inherits many methods for processing the underlying array of Eloquent model.

Of course, collections are also iterators, allowing you to loop them like PHP arrays:

 $users = App\User::where('active', 1)->get(); foreach ($users as $user) { echo $user->name; }

However, collections are more powerful than arrays because they provide various mapping/simplification operations using intuitive interfaces. For example, we can remove all invalid models and aggregate the names of the remaining users in the following ways:

 $users = App\User::where('active', 1)->get(); $names = $users->reject(function ($user) { return $user->active === false; })->map(function ($user) { return $user->name; });
Note: Although most Eloquent collections return a new Eloquent collection instance pluck keys zip collapse flatten and flip Method returns Collection base class example. Similarly, if map The collection returned by the operation does not contain any Eloquent model and will be automatically converted to the collection base class.

Available methods

Collection base class

All Eloquent collections inherit from the base class of the Laravel collection object, so they inherit the powerful methods provided by all the base collection classes: Collection Methods

Custom Collection

If you need to use custom collection objects in your own extended methods, you can override the newCollection method:

 <? php namespace App; use App\CustomCollection; 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 CustomCollection($models); } }

Well defined newCollection Method, Eloquent returns the Collection You will get custom collections for all instances. If you want to use custom collections in each model in the application, you need to override them in the model base class newCollection method.


give the thumbs-up Cancel Like Collection Cancel Collection

<<Previous: Advanced Chapter: Managing Association Relationship Using Eloquent Model

>>Next: Formatting model data with accessors and modifiers