laravel collection to array

后端 未结 6 1544
清歌不尽
清歌不尽 2020-12-03 00:38

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.<

相关标签:
6条回答
  • 2020-12-03 00:47

    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;
    }
    
    0 讨论(0)
  • 2020-12-03 00:49

    Try collect function in array like:

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

    this methods can help you

    toArray() with collect()

    0 讨论(0)
  • 2020-12-03 01:01

    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

    0 讨论(0)
  • 2020-12-03 01:01

    Use collect($comments_collection).

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

    0 讨论(0)
  • 2020-12-03 01:03

    Try this:

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

    see this can help you
    toArray() method in Collections

    0 讨论(0)
  • 2020-12-03 01:09

    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.

    0 讨论(0)
提交回复
热议问题