Using Maps In Laravel Collections

Let's assume that we are recording your records using a model.


  1. $users = User::all();

  2. $uppercasedNames = $users->map(function ($user) {

  3.    return strtoupper($user->name);

  4. });


An array data can be processed


  1. $collection = collect([1, 2, 3, 4, 5]);


  2. $mapped = $collection->map(function ($item, $key) {

  3.    return $item * 2;

  4. });


Another example


  1. $users = [

  2.    ['name' => 'John', 'age' => 30],

  3.    ['name' => 'Alice', 'age' => 25],

  4.    ['name' => 'Bob', 'age' => 35]

  5. ];


  6. $modifiedUsers = collect($users)->map(function ($user) {

  7.    return [

  8.        'name' => strtoupper($user['name']),

  9.        'age' => $user['age'] * 2

  10.    ];

  11. });