Home » Php » laravel collection to array

laravel collection to array

Posted by: admin November 29, 2017 Leave a comment

Questions:

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?

Answers:

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()

Questions:
Answers:

Try this

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

see this can help you
collections

Questions:
Answers:

use collect($comments_collection) or use
try json_decode($comments_collection) to convert to json.