Laravel Collections Using Map to manipulate each element in a collection


Example

Often you need to change the way a set of data is structured and manipulate certain values.

In the example below we got a collection of books with an attached discount amount. But we much rather have a list of books with a price that's already discounted.

$books = [
    ['title' => 'The Pragmatic Programmer', 'price' => 20, 'discount' => 0.5],
    ['title' => 'Continuous Delivery', 'price' => 25, 'discount' => 0.1],
    ['title' => 'The Clean Coder', 'price' => 10, 'discount' => 0.75],
];

$discountedItems =  collect($books)->map(function ($book) {
   return ['title' => $book["title"], 'price' => $book["price"] * $book["discount"]];
});

//[
//    ['title' => 'The Pragmatic Programmer', 'price' => 10],
//    ['title' => 'Continuous Delivery', 'price' => 12.5],
//    ['title' => 'The Clean Coder', 'price' => 5],
//]

This could also be used to change the keys, let's say we wanted to change the key title to name this would be a suitable solution.