How to use Laravel Collection Map Method
In this tutorial, we will learn How to use Laravel Collection Map Method. Are you looking for an example of How to use the Laravel Collection Map Method example? I give a simple way to create the Laravel collection map method. We will use the Laravel default collection map. we can use the map() method to perform an action on each element of Laravel Collections. The map() method used will not modify the original collection, instead, it will return a new collection with all the changes.
The Laravel map method will give a callback function to each element of a collection. and the callback function mainly modifies the item and creates a new Laravel collection for them.
I will give you simple examples of how to use the Laravel map collection. so you can easily use Laravel 5, Laravel 6, Laravel 7, Laravel 8, and Laravel 9 applications.
Syntax
$collecton->map(
Callback
);
Laravel Collection map()
public function index() {
$collection = collect(["worner", "josep", "joi", "die", "kell"]);
$changes = $collection->map(function($item, $key) {
return strtoupper($item);
});
dd($changes);
}
Output
Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[0] => WORNER
[1] => JOSEP
[2] => JOI
[3] => DIE
[4] => KELL
)
)
Laravel Eloquent Collection Map
Laravel Eloquent Collection Map when we need to change the column name, add string or etc, so you can easily use the map method.
public function index() {
$collection = User::get();
$users = $collection->map(function($item, $key) {
return [
'id' => $item->id,
'name' => "dev-".$item->name,
'creation_date' => $item->created_at->format('d/m/Y')
];
});
dd($users);
}
Output
Illuminate\Support\Collection Object
(
[items:protected] => Array(
[0] => Array(
[id] => 1
[name] => dev-worner
[creation_date] => 09/06/2022
)
[1] => Array(
[id] => 2
[name] => dev-josep
[creation_date] => 09/06/2022
)
)
)