3 simple ways to use Collection’s map method

Sky Chin
1 min readSep 28, 2018

--

Photo by Victoria Kure-Wu on Unsplash

Laravel’s Collection has many powerful methods that can help you to do the complex tasks.

Map method applies a callback function to each of the items in the collection. In the callback function, you can modify the item before returning it.

Here are three simple ways you can use the map method.

Given you have a collection of fruits.

$fruits = collect(['apple', 'orange', 'watermelon']);

You can transform the value in the collection.

You turn the fruits into big size.

$bigFruits = $fruits->map(function($fruit) {
return strtoupper($fruit);
});
// ['APPLE', 'ORANGE', 'WATERMELON']

Besides, you can perform checking in the callback function.

You don’t like to eat the orange, so you replace it with the grape.

$noOrange = $bigFruits->map(function($fruit) {
if ($fruit === 'ORANGE') {
return 'GRAPE';
}
return $fruit;
});
// ['APPLE', 'GRAPE', 'WATERMELON']

Otherwise, you can modify the item. For example, modify the string collection into associative array collection.

You put the fruits into the basket in order.

$fruitBasket = $noOrange->map(function($fruit, $index) {
return [
'name' => $fruit,
'seq' => $index + 1
];
});
// [['name': 'APPLE', 'seq' => 1], ['name': 'GRAPE', 'seq' => 2], ['name': 'WATERMELON', 'seq' => 3]]

This article was originally posted at TribeHired.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Sky Chin
Sky Chin

Written by Sky Chin

Engineering Manager @ Mindvalley

No responses yet

Write a response