ChatGPT解决这个技术问题 Extra ChatGPT

laravel collection to array

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?


D
Drudge Rajen

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.


Sometimes this method throws exception when there is no data.
Can you tell me the case where it throws an expection. I tried with null data but doesn't throw an exception
Nit-pick: if the array elements implement \Illuminate\Contracts\Support\Arrayable, they will be converted into arrays, too, recursively. That includes Eloquent models.
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.
@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.
e
eithed

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

but is it in array?
Yes @JovylleBermudez. It is an Array of Objects
This is the right solution for me since I need an array of models, not an array of arrays.
İ
İlker Ergün

Try this:

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

see this can help you
toArray() method in Collections


If query does not have any record then toArray() does not work on NULL record and returns error.
A
Akshay Kulkarni

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


W
Wolverine

Use collect($comments_collection).

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


F
Ferhat KOÇER

Try collect function in array like:

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

this methods can help you

toArray() with collect()


If query does not have any record then toArray() does not work on NULL record and returns error.