Common Laravel Collection Methods and Their Usage

This tutorial explains Laravel's powerful Collection class, demonstrating how to create collections with the collect helper and use methods such as filter, search, chunk, map, zip, whereNotIn, max, pluck, each, tap, pipe, contains, forget, and avg to manipulate data without additional database queries.

php Courses
php Courses
php Courses
Common Laravel Collection Methods and Their Usage

Laravel Eloquent returns a Collection object that provides many useful methods for filtering, modifying, and analyzing data. You can also create a collection directly from an array using the collect helper.

Key methods demonstrated include:

filter() : Returns a new collection containing items that satisfy a callback condition. Example:

$filter = $collection->filter(function($value, $key) {
    if ($value['user_id'] == 2) {
        return true;
    }
});
$filter->all();

search() : Finds the key of a given value or returns false if not found. It supports strict comparison and custom callbacks. Example:

$names = collect(['Alex', 'John', 'Jason', 'Martyn', 'Hanlin']);
$names->search('Jason'); // returns 2

chunk() : Splits a collection into smaller collections of a given size. Example:

$prices = collect([18, 23, 65, 36, 97, 43, 81]);
$prices = $prices->chunk(3)->toArray();

dump() : Dumps the collection for debugging.

map() : Transforms each item using a callback and returns a new collection. Example:

$changed = $collection->map(function($value, $key) {
    $value['user_id'] += 1;
    return $value;
});
$changed->all();

zip() : Merges the collection with another array by index.

whereNotIn() : Filters out items whose given key's value is in the supplied array.

max() : Retrieves the maximum value for a given key.

pluck() : Extracts a single column's values from the collection. Example: $titles = $collection->pluck('title')->all(); each() : Iterates over the collection, executing a callback for each item.

tap() : Passes the collection to a callback without altering the original instance.

pipe() : Sends the collection through a callback and returns the callback's result.

contains() : Checks if a value or key/value pair exists in the collection.

forget() : Removes an item by its key.

avg() (or average): Calculates the average of numeric values for a given key.

These methods allow you to manipulate data efficiently after retrieving it from the database, reducing the need for additional queries.

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.

BackendPHPCollectionsLaravelEloquentdata manipulation
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

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.