laravel collection->map code example
Example 1: collection laravel filter
$collection = collect([1, 2, 3, 4]);
$filtered = $collection->filter(function ($value, $key) {
return $value > 2;
});
$filtered->all();
Example 2: collection map laravel
$data = [];
$query = users::where('id', 1)->get();
$map = $query->map(
function($items){
$data['user_firstName'] = $items->firstName;
$data['user_lastName'] = $items->lastName;
return $data;
}
);
return $map;
Example 3: laravel reduce
$collection = collect([1, 2, 3]);
$total = $collection->reduce(function ($carry, $item) {
return $carry + $item;
});
$total = $collection->reduce(function ($carry, $item) {
return $carry + $item;
}, 4);
Example 4: eloquent map collection