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?
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()
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
Try this:
$comments_collection = $post->comments()->get()->toArray();
see this can help you
toArray() method in Collections
Source: Stackoverflow.com