Laravel Collection Map Method Example
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
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. 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, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Collection Concat Method Example
- Laravel Collection first() and firstWhere() Methods Example
- Laravel Collection SortByDesc Tutorial with Examples
- Laravel Collection SortBy Tutorial with Examples
- Laravel Collection Merge | How to Merge Two Eloquent Collection?
- Laravel Collection Unique | Remove Duplicates from Collection Laravel
- Laravel Collection Search Method Example
- Laravel Collection Filter Method Example