126

I have two models, Post and Comment; many comments belong to a single post. I'm trying to access all comments associated with a post as an array.

I have the following, which gives a collection.

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

How would I turn this $comments_collection into an array? Is there a more direct way of accessing this array through eloquent relationships?

datavoredan
  • 3,536
  • 9
  • 32
  • 48

8 Answers8

213

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.

Drudge Rajen
  • 7,584
  • 4
  • 23
  • 43
  • Sometimes this method throws exception when there is no data. – Akshay Kulkarni Jan 22 '18 at 10:44
  • Can you tell me the case where it throws an expection. I tried with null data but doesn't throw an exception – Tijan Manandhar Apr 09 '18 at 09:54
  • 1
    Nit-pick: if the array elements implement `\Illuminate\Contracts\Support\Arrayable`, they will be converted into arrays, too, recursively. That includes Eloquent models. – nevvermind Feb 25 '19 at 15:21
  • 20
    This shouldn't be the top answer. `->toArray()` does not convert the collection to an array, it converts the whole contents into arrays, including the items of the collection. `->all()` should be the accepted answer. – Sebastien C. Jan 23 '20 at 05:16
  • @SebastienC. OP had asked the way to convert collection to an array. So, `toArray()` is fine for that. Also, I have updated the answer with documentation. – Drudge Rajen Jan 24 '20 at 03:40
  • If query does not have any record then toArray() does not work on NULL record and returns error. – Kamlesh Jun 06 '21 at 08:45
  • Don't use `toArray()`. The returned array is more of a collection. The correct answer should be using `all()` – PhillipMwaniki Dec 30 '21 at 10:06
41

Use all() method - it's designed to return items of Collection:

/**
 * Get all of the items in the collection.
 *
 * @return array
 */
public function all()
{
    return $this->items;
}
eithed
  • 3,933
  • 6
  • 40
  • 60
11

Try this:

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

see this can help you
toArray() method in Collections

İlker Ergün
  • 68
  • 2
  • 7
paranoid
  • 6,799
  • 19
  • 49
  • 86
  • If query does not have any record then toArray() does not work on NULL record and returns error. – Kamlesh Jun 06 '21 at 08:45
2

you can do something like this

$collection = collect(['name' => 'Desk', 'price' => 200]);
$collection->toArray();

Reference is https://laravel.com/docs/5.1/collections#method-toarray

Originally from Laracasts website https://laracasts.com/discuss/channels/laravel/how-to-convert-this-collection-to-an-array

Akshay Kulkarni
  • 722
  • 2
  • 10
  • 16
0

Use collect($comments_collection).

Else, try json_encode($comments_collection) to convert to json.

Wolverine
  • 1,712
  • 1
  • 15
  • 18
TechPotter
  • 579
  • 8
  • 14
0

Just doing an all() on the collection returns an array, like so:

$comments_collection = $post->comments()->all();

I'm on Laravel 10.5.0 and this works well for me.

Maklas
  • 124
  • 1
  • 6
0

For nested collection (for example when we call query builder get method) we can make things simpler by adding a macro to collection type. we assume our collection is collection of stdClass objects.

for this, add this code to the boot() method in AppServiceProvider:

Collection::macro('toNestedArray', function () {
        return $this->transform(function ($item, int $key) {
            return (array)$item;
        });
    });

just note this code would convert just one level nested stdClass to array. you can tune the code for your needs

Amin.Qarabaqi
  • 661
  • 7
  • 19
-2

Try collect function in array like:

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

this methods can help you

toArray() with collect()

Ferhat KOÇER
  • 3,890
  • 1
  • 26
  • 26
  • If query does not have any record then toArray() does not work on NULL record and returns error. – Kamlesh Jun 06 '21 at 08:45