Understanding Laravel Eloquent Collections and Their Methods

This article explains how Laravel Eloquent returns Collection objects, demonstrates iterating and chaining collection methods such as reject and map, lists the extensive base collection API, and shows how to create custom collections by overriding the newCollection method in a model.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Understanding Laravel Eloquent Collections and Their Methods

Introduction

All multi‑result sets returned by Eloquent are instances of Illuminate\Database\Eloquent\Collection, including results retrieved via the get method or through relationship access. The collection class extends Laravel’s base collection, inheriting dozens of methods for elegant array handling.

Collections can be iterated like simple PHP arrays:

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

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

Beyond simple iteration, collections provide chainable map / reject operations. For example, removing inactive users and gathering the remaining names:

$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 a new Eloquent collection instance, except methods such as pluck , keys , zip , collapse , flatten , and flip , which return a base collection instance. If a map operation yields no Eloquent models, the result is automatically converted to a base collection.

Available Methods

Base Collection

All Eloquent collections inherit Laravel’s base collection, which offers a large set of powerful methods, including:

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, 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

If you need a custom Collection in your own extensions, override the newCollection method in your model:

<?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);
    }
}

After defining newCollection, any Eloquent query will return instances of your custom collection. To use the same custom collection across all models, override newCollection in a base model that all other models extend.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

backend-developmentORMPHPCollectionsLaravelEloquent
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.