Перевод немного отстаёт от оригинала
Eloquent: коллекции
Все методы Eloquent, которые возвращают не одну, а несколько моделей (включая запросы к отношениям), на самом деле возвращают не массив с этими моделями, а объект Illuminate\Database\Eloquent\Collection
. Этот класс является расширением класса стандартных коллекций Laravel .
Так как объект коллекций итерируемый, вы можете работать с ним в циклах как будто это обычный php-массив:
$users = App\User::where('active' , 1 )->get();
foreach ($users as $user) {
echo $user->name;
}
However, collections are much more powerful than arrays and expose a variety of map / reduce operations using an intuitive interface. For example, let's remove all inactive models and gather the first name for each remaining user:
Однако коллекции, в отличие от массивов, имеют массу дополнительных очень удобных фич. Например, давайте отфильтруем из результата запроса все неактивные модели и у оставшихся моделей соберем имена пользователей:
$users = App\User::where('active' , 1 )->get();
$names = $users->reject(function ($user) {
return $user->active === false ;
})
->map(function ($user) {
return $user->name;
});
Базовые методы коллекций
Так как коллекции Eloquent являются расширением основного класса коллекций Laravel ? они наследуют все его методы:
[all](/docs/5.1/collections#method-all)
[chunk](/docs/5.1/collections#method-chunk)
[collapse](/docs/5.1/collections#method-collapse)
[contains](/docs/5.1/collections#method-contains)
[count](/docs/5.1/collections#method-count)
[diff](/docs/5.1/collections#method-diff)
[each](/docs/5.1/collections#method-each)
[filter](/docs/5.1/collections#method-filter)
[first](/docs/5.1/collections#method-first)
[flatten](/docs/5.1/collections#method-flatten)
[flip](/docs/5.1/collections#method-flip)
[forget](/docs/5.1/collections#method-forget)
[forPage](/docs/5.1/collections#method-forpage)
[get](/docs/5.1/collections#method-get)
[groupBy](/docs/5.1/collections#method-groupby)
[has](/docs/5.1/collections#method-has)
[implode](/docs/5.1/collections#method-implode)
[intersect](/docs/5.1/collections#method-intersect)
[isEmpty](/docs/5.1/collections#method-isempty)
[keyBy](/docs/5.1/collections#method-keyby)
[keys](/docs/5.1/collections#method-keys)
[last](/docs/5.1/collections#method-last)
[map](/docs/5.1/collections#method-map)
[merge](/docs/5.1/collections#method-merge)
[pluck](/docs/5.1/collections#method-pluck)
[pop](/docs/5.1/collections#method-pop)
[prepend](/docs/5.1/collections#method-prepend)
[pull](/docs/5.1/collections#method-pull)
[push](/docs/5.1/collections#method-push)
[put](/docs/5.1/collections#method-put)
[random](/docs/5.1/collections#method-random)
[reduce](/docs/5.1/collections#method-reduce)
[reject](/docs/5.1/collections#method-reject)
[reverse](/docs/5.1/collections#method-reverse)
[search](/docs/5.1/collections#method-search)
[shift](/docs/5.1/collections#method-shift)
[shuffle](/docs/5.1/collections#method-shuffle)
[slice](/docs/5.1/collections#method-slice)
[sort](/docs/5.1/collections#method-sort)
[sortBy](/docs/5.1/collections#method-sortby)
[sortByDesc](/docs/5.1/collections#method-sortbydesc)
[splice](/docs/5.1/collections#method-splice)
[sum](/docs/5.1/collections#method-sum)
[take](/docs/5.1/collections#method-take)
[toArray](/docs/5.1/collections#method-toarray)
[toJson](/docs/5.1/collections#method-tojson)
[transform](/docs/5.1/collections#method-transform)
[unique](/docs/5.1/collections#method-unique)
[values](/docs/5.1/collections#method-values)
[where](/docs/5.1/collections#method-where)
[whereLoose](/docs/5.1/collections#method-whereloose)
[zip](/docs/5.1/collections#method-zip)
Если вам нужно расширить класс коллекций Eloquent, добавив туда свои методы, переопределите метод newCollection
в нужной модели:
<?php namespace App ;
use App \CustomCollection ;
use Illuminate \Database \Eloquent \Model ;
class User extends Model
{
public function newCollection (array $models = [])
{
return new CustomCollection($models);
}
}
Если вам нужно переопределить класс коллекций для всех моделей, переопределите его в базовой модели, и все свои модели наследуйте от этой базовой модели.