w3resource

Laravel (5.7) Eloquent Collections

Eloquent Collections

In this tutorial we are going to guide you through Laravel?s Eloquent Collections, this tutorial will be divided into Introduction, Available Methods and then custom collections.

Introduction

In laravel all of the multi-result sets that are returned by Eloquent are instances of the Illuminate\Database\Eloquent\Collection object, this includes results that are retrieved via the get method or they are accessed via a relationship. The Eloquent collection object will extend the Laravel base collection, hence it will naturally inherit dozens of methods used fluently work with the underlying array of Eloquent models.

All collections also serves as iterators, enabling you to loop over them as if they were simple PHP arrays:

$users = App\User::where('active', 1)->get();

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

Warning:While most Eloquent collection methods will return a new instance of an Eloquent collection, the pluck, keys, zip, collapse, flatten and flip methods will all return a base collection instance. Likewise, if we have a case where a map operation returns a collection that does not contain any Eloquent models, the map operation will be automatically cast to a base collection.

Available Methods

The Base Collection

All the Eloquent collections will extend the base Laravel collection object; therefore, they will inherit all of the powerful methods provided by the base collection class these methods include:

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 Collections

There are certain case when you need to use a custom Collection object with your own extension methods, in such cases you may override the newCollection method on your model:

<?php

namespace App;

use App\CustomCollection;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * this will create a new Eloquent Collection instance.
     *
     * @param  array  $models
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function newCollection(array $models = [])
    {
        return new CustomCollection($models);
    }
}

Once you have successfully defined a newCollection method, you will receive an instance of your custom collection anytime that Eloquent returns a Collection instance of that model. If you would love to use a custom collection for every model that is in your application, you should override the newCollection method on a base model class that is extended by every model that is in your application.



Share this Tutorial / Exercise on : Facebook and Twitter