Laravel Collection Map Method Example

By Hardik Savani | April 19, 2020 | 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 and laravel 8 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
My name is Hardik Savani. I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.
Follow Me: Github Twitter
***Do you want me hire for your Project Work? Then Contact US.

We are Recommending you: