Eloquent collection


Custom collection

  • ##Introduction
  • All multiple result sets returned by Eloquent are instances of the
  • Illuminate\Database\Eloquent\Collection object, including those retrieved through the get
  • method or accessed through The results obtained by the association relationship. Eloquent's collection object inherits Laravel's collection base class, so it naturally also inherits dozens of methods that can elegantly handle the underlying array of Eloquent models.

Moreover, all collections can be used as iterators, and you can traverse them just like traversing simple PHP arrays:

$users = App\User::where('active', 1)->get();
foreach ($users as $user) { 
   echo $user->name;
 }
However, collections are more powerful than arrays, and they are more intuitive through The interface exposes operations such as map/reduce that can be called in a chain. For example, let's remove all inactive users and collect the names of the remaining users:

$users = App\User::all();
$names = $users->reject(function ($user) { 
   return $user->active === false;
 })->map(function ($user) { 
   return $user->name;
 });
{note} Most Eloquent collection methods return new Eloquent collection instances, but

pluck# Exceptions are the ##,

keys

, zip, collapse,

flatten

and

flip

methods, which return a collection Base class instance. Likewise, if the collection returned by the

map
operation does not include any Eloquent models, it is automatically converted to a collection base class.

Available methods

Collection Base Class

All Eloquent objects inherit the base Laravel collection object; therefore, they also inherit all the powerful methods provided by the collection base class:

all
average
avg
chunk
collapse
combine
concat
contains
containsStrict
count
crossJoin
dd
diff
diffKeys
dump
each
eachSpread
every
except
filter
first
flatMap
flatten
flip
forget
forPage
get
groupBy
has
implode
intersect
isEmpty
isNotEmpty
keyBy
keys
last
map
mapInto
mapSpread
mapToGroups
mapWithKeys
max
median
merge
min
mode
nth
only
pad
partition
pipe
pluck
pop
prepend
pull
push
put
random
reduce
reject
reverse
search
shift
shuffle
slice
some
sort
sortBy
sortByDesc
splice
split
sum
take
tap
toArray
toJson
transform
union
unique
uniqueStrict
unless
values
when
where
whereStrict
whereIn
whereInStrict
whereNotIn
whereNotInStrict
zip

##Custom Collection

If you need it in your own extension method With a custom

Collection object, you can override the newCollection method in your model:

<?php
    namespace App;
    use App\CustomCollection;
    use Illuminate\Database\Eloquent\Model;
    class User extends Model{   
     /**
     * 创建一个新的 Eloquent 集合实例对象。
     *
     * @param  array  $models
     * @return \Illuminate\Database\Eloquent\Collection
     */    
     public function newCollection(array $models = [])  
       {   
            return new CustomCollection($models);    
        }
    }

Once you have defined the

newCollection method , your custom collection instance can be obtained at any time in the Collection instance of the model returned by Eloquent. If you want to use a custom collection in every model in your application, you should override the newCollection method in the model base class that all models inherit from.

This article was first published on the
LearnKu.com website.