Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change value of last item in collection?

lets say you have this simple collection:

 $c = collect([
     ['active'=>false],
     ['active'=>false],
     ['active'=>false],
    ]
 );

I want to change the last item to set active to true is there any easy collectionish way rather than something like:

$collection->toArray();
$collection[count($collection)-1]['active'] = true;
$newCollection = collect($collection);
like image 554
Amir Bar Avatar asked Oct 31 '25 11:10

Amir Bar


1 Answers

First of all laravel collections are array accessible and you don't need to call toArray. As for you issue you can do this:

$last = $collection->pop(); $last['active'] = true $collection->push($last)

https://laravel.com/docs/5.2/collections#method-pop https://laravel.com/docs/5.2/collections#method-push

like image 197
Bogdan Koliesnik Avatar answered Nov 03 '25 09:11

Bogdan Koliesnik