map()

map() transforms every item and returns a new collection.

Syntax$collection->map(function ($item) { return ...; });

The map() method loops over the collection, passes each item to your callback, and builds a new collection from the returned values. The original collection is left unchanged.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A checkout service maps over a collection of cart items to apply a 10% discount to each unit price before totalling the order.
  • An API serialiser maps Eloquent User models to plain arrays containing only the public fields before returning the JSON response.
  • A data-import pipeline maps raw CSV rows to validated DTO objects, transforming each record into a strongly-typed structure in one pass.

More examples

Double every number in a collection

Basic map() that transforms each element by multiplying it by two, returning a new collection.

Example · php
$numbers = collect([1, 2, 3, 4]);

$doubled = $numbers->map(fn($n) => $n * 2);
// => Collection [2, 4, 6, 8]

Shape Eloquent models for an API

Maps each User model to a plain array with only the public fields, keeping the API response shape explicit.

Example · php
$users = User::all()->map(fn($user) => [
    'id'    => $user->id,
    'name'  => $user->name,
    'email' => $user->email,
]);

return response()->json($users);

Apply a discount to cart items

Applies a 10% discount to every cart item's price and returns a new collection with updated values.

Example · php
$cart = collect([
    ['name' => 'T-Shirt', 'price' => 30.00],
    ['name' => 'Jeans',   'price' => 80.00],
]);

$discounted = $cart->map(function ($item) {
    $item['price'] = round($item['price'] * 0.90, 2);
    return $item;
});
// T-Shirt => 27.00, Jeans => 72.00

Discussion

  • Be the first to comment on this lesson.