Laravel Collection Map Method Example

By Hardik Savani April 16, 2024 Category : 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...

Shares