Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 294
datavoredan Avatar asked Feb 09 '16 06:02

datavoredan


People also ask

What is toArray () in Laravel?

toArray is a model method of Eloquent, so you need to a Eloquent model, try this: User::where('name', '=', 'Jhon')->get()->toArray(); http://laravel.com/docs/eloquent#collections. Follow this answer to receive notifications.

How do I combine two collections in Laravel?

Laravel collection merge() method merge any given array to first collection array. If the first collection is indexed array, the second collection will be added to the end of the new collection. The merge() method can accept either an array or a Collection instance.


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

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.

like image 73
Drudge Rajen Avatar answered Sep 28 '22 07:09

Drudge Rajen