moses toh
moses toh

Reputation: 13172

How to add number in collection laravel?

If I dd($items), the result like this :

enter image description here

I want to add number to each array

So the first array, exist key number with value 1

The second array, exist key number with value 2

etc

I try like this :

$items->map(function ($item) {
    $item['number'] = 1;
    return $item;
});

Number does not increase. I'm confused to make the counter

How can I solve this problem?

Upvotes: 2

Views: 3983

Answers (3)

rkj
rkj

Reputation: 8287

You can try it like this

$newItems = $items->map(function ($item, $index) {
    $item['number'] =  $index + 1;
    return $item;
});

Edit: Based on comment (I don't recommend it because then you can not get benefit of eloquent model. It simply return you an array )

$newItems = $items->map(function ($item, $index) {
    $number = ['number' =>  $index + 1];
    return $number + $item->toArray();
});

Upvotes: 6

Znar
Znar

Reputation: 369

you can use array_merge

$newItems = $items->map(function ($item, $index) {

  return array_merge(array("number" =>  $index + 1), $item);;
});

Upvotes: 0

Arnab Rahman
Arnab Rahman

Reputation: 1013

 $counter=1;
 $items->map(function ($item) use(&$counter){
   $item['number'] = $counter++;
   return $item;
});

Upvotes: 0

Related Questions