欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

laravel 5 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?


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?


正确答案

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

Try this

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

see this can help you
collections

shareimprove this answeredited Feb 9 '16 at 6:11  answered Feb 9 '16 at 6:06paranoid1,82941138
 

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

shareimprove this answeranswered Apr 23 at 11:02Peter Tiriwo165
 

来自 https://stackoverflow.com/questions/35284974/laravel-collection-to-array


普通分类: