laravel collection to array

PhpArraysLaravelEloquent

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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.

Solution 2 - Php

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;
}

Solution 3 - Php

Try this:

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

see this can help you
toArray() method in Collections

Solution 4 - Php

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

Solution 5 - Php

Use collect($comments_collection).

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

Solution 6 - Php

Try collect function in array like:

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

this methods can help you

toArray() with collect()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondatavoredanView Question on Stackoverflow
Solution 1 - PhpDrudge RajenView Answer on Stackoverflow
Solution 2 - PhpeithedView Answer on Stackoverflow
Solution 3 - PhpparanoidView Answer on Stackoverflow
Solution 4 - PhpAkshay KulkarniView Answer on Stackoverflow
Solution 5 - PhpTechPotterView Answer on Stackoverflow
Solution 6 - PhpFerhat KOÇERView Answer on Stackoverflow