Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The best way to make eloquent collection to custom array

What is the best way to make Object::all() to array('object_id', 'object_name')? I need a nice code to use eloquent collection for SELECT: {{ Form:select('objects', $custom_array) }}. Is a for loop the only way to do that ?

like image 680
Benas Radzevicius Avatar asked May 13 '13 13:05

Benas Radzevicius


People also ask

How to get an array of eloquent models?

So to get an Array of Eloquent models you need to use SomeModel::all ()->all (); Show activity on this post. My first thought was $collection->toArray () but that also converts the Eloquent models to arrays. But the docs say that $collection->all () should avoid that. toArray also converts all of the collection's nested objects to an array.

What is eloquent collection in Laravel?

Laravel Eloquent collection object extends the base collection, so it naturally inherits the dozens of methods used to work with an underlying array of Eloquent models fluently.

How do I get a custom collection instance of eloquent?

Once you have defined the newCollection method, you will receive an instance of your custom collection anytime Eloquent returns the collection instance of that model.

Where are the multi-result sets returned by eloquent stored?

All multi-result sets returned by Eloquent are instances of the Illuminate\Database\Eloquent\Collection object, including results retrieved via the get method or accessed via a relationship.


1 Answers

I think you are looking for toArray():

User::all()->toArray();

http://four.laravel.com/docs/eloquent#converting-to-arrays-or-json

To get an array that can be directly used with Form::select(), you can use the following:

$contacts = Contact::orderBy('name')->lists('name', 'id');
$contacts = count($contacts) > 0 ? $contacts : array();

{{ Form::select('contact', $contacts) }}
like image 188
Holger Weis Avatar answered Jan 31 '23 18:01

Holger Weis