ItSolutionStuff.com

Laravel Collection Map Method Example

By Hardik Savani • April 16, 2024
Laravel

Are you looking for example of laravel collection map example. i explained simply about laravel eloquent collection map. We will use laravel collection map. This article goes in detailed on laravel map example.

The map method will given callback function to each element of a collection. The callback function will modify a item and create a new Laravel collection.

I will give you simple examples of map colletion in laravel. so you can easily use it with your laravel 5, laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 application. so let's see bellow example that will helps you lot.

Syntax:

$collecton->map(

Callback

);

Laravel Collection map() Example

public function index()

{

$collection = collect(["one", "two", "three", "four", "five"]);

$modified = $collection->map(function($item, $key) {

return strtoupper($item);

});

dd($modified);

}

Output:

Illuminate\Support\Collection Object

(

[items:protected] => Array

(

[0] => ONE

[1] => TWO

[2] => THREE

[3] => FOUR

[4] => FIVE

)

)

Laravel Eloquent Collection Map

If you need to change column name for your api response or front end side you can easily use map method for change that as like bellow:

public function index()

{

$collection = User::get();

$modified = $collection->map(function($item, $key) {

return [

'id' => $item->id,

'name' => $item->name,

'creation_date' => $item->created_at->format('m/d/Y')

];

});

dd($modified);

}

Output:

Illuminate\Support\Collection Object

(

[items:protected] => Array

(

[0] => Array

(

[id] => 1

[name] => Hardik

[creation_date] => 04/19/2020

)

[1] => Array

(

[id] => 2

[name] => HD Surgon

[creation_date] => 03/28/2020

)

)

)

I hope it can help you...

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Laravel Collection Concat Method Example

Read Now →

Laravel Collection first() and firstWhere() Methods Example

Read Now →

Laravel Collection SortByDesc Tutorial with Examples

Read Now →

Laravel Collection SortBy Tutorial with Examples

Read Now →

Laravel Collection Merge | How to Merge Two Eloquent Collection?

Read Now →

Laravel Collection Unique | Remove Duplicates from Collection Laravel

Read Now →

Laravel Collection Search Method Example

Read Now →

Laravel Collection Filter Method Example

Read Now →