幼虫采集到数组

我有两个模型,PostComment; 许多评论属于一个单一的职位。我试图以数组的形式访问与帖子相关的所有评论。

我有以下的,这给了一个集合。

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

如何将这个 $comments_collection转换为数组?有没有更直接的方法通过雄辩的关系访问这个数组?

259612 次浏览

Try this:

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

see this can help you
toArray() method in Collections

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.

Use collect($comments_collection).

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

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

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

Try collect function in array like:

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

this methods can help you

toArray() with collect()