Laravel Collection to Array

laravel collection to array

You can use toArray() of eloquent as below.

The toArray method converts the collection into a plain PHP array. If the collection's values are Eloquent models, the models will also be converted to arrays

$comments_collection = $post->comments()->get()->toArray()

From Laravel Docs:

toArray also converts all of the collection's nested objects that are an instance of Arrayable to an array. If you want to get the raw underlying array, use the all method instead.

How to update an array inside of a Laravel Collection?

U can´t update the array cause is passed by value, for modify the content u need pass by reference like this:

foreach($data as &$item){
$item['status'] = 'NEW';
}

don´t forget to unset the reference:

unset($item);

I think it's best to avoid this pitfall altogether and just write foreach loops that have to manipulate the original array the normal way:

foreach($data as $index => $entry) {
$data[$index] = ...
}

here you will get more info about reference variables.

Laravel collection containing model to array

only() will return an array of specified columns only. And toArray() will transform the collection to array:

$collection->map(function($i) {
return array_values($i->only('username', 'email', 'date'));
})->toArray();

Mix an array on Laravel Collection

If you're trying to interleave items based on their type you can try :

$collection = collect($array)->groupBy(function ($value) {
return gettype($value);
});

$interleaved = $collection->first()->zip($collection->last())->flatten()->filter();

This will:

  1. Group items by type
  2. Take the first group and zip it with the last group (this assumes you have exactly 2 groups)
  3. It will then flatten the result and filter out null values

Note: You might need to add a check to determine if the string group is first or last and adapt accordingly.

Adding attributes to laravel collection

You can't use ->put in an ->each loop for this case, because ->each does not loop the items by reference. So all modifications to the item are lost after the loop.

You can map the array to return your actual $item merged with the extra key amount. The correct method to use is ->map.

$collection = $collection->map(function($item) {
return array_merge($item, [
'amount' => $item->price * $item->qty;
]);
});

https://laravel.com/docs/9.x/collections#method-map



Related Topics



Leave a reply



Submit