Laravel Eloquent将数据提取到自定义数组中

I've tried searching for a way to do this with Laravel, and i'm sure it's more than capable (Maybe i've been searching for it using incorrect terms)..

I'm trying to extract table data to be used in Laravels built-in form creator:

$clusters = Cluster::get(array('id','name'));

Into:

{{ Form::select('cluster', $clusters,Input::old('cluster'), array('id' => 'cluster')) }}

But currently, I get a dropdown with JSON in it, and if I use toArray() it doesn't use the ID numbers from the JSON array, it applies new ID numbers, then puts the data in an array:

Badly formed array using toArray from JSON object

Can anyone point me in the right direction to form arrays properly from Eloquent extractions? I've been using this bit of code which feels meaningless:

$clust = array();
foreach($clusters as $key => $cl) {
  $clust[$cl['id']] = $cl['location'];
}

Thanks

Use lists(), which will return an array of column values, and an optional identifier for them.

// Controller
$clusters = Cluster::lists('name', 'id');

// View
{{ Form::select('cluster', $clusters) }}

lists() is a Query Builder method. All Query Builder methods are available to Eloquent models.


FYI: When using the Form helpers, it will automatically fill the old input if it exists, so you don't need to specify it. Also, the helper will generate an ID based on the name of the element automatically, so that can be excluded, also.

This is a combination of using a controller to get the data and create the view, and then using the view to make the form.

In your controller:

$clusters = Cluster::select('id', 'name')->get(); // Or however you pull it
// Transfer that data to a view, example views/clusters.blade.php
return View::make('clusters')->with(array('clusters' => $clusters));

Then on your view, use $clusters to generate any form options you need. For example a dropdown can be made as such:

// Using HTML tags
<select class="form-control" name="cluster">
@foreach($clusters AS $cluster)
<option value="{{ $cluster->id }}" {{ (Input::old('cluster') == $cluster->name) ? "selected":"" }}> {{ $cluster->name }} </option>
@endforeach
</select>

// Using Laravel Form Builder
{{ Form::select('cluster', $clusters) }} // Not sure how you'd handle Input::old

Hope that sheds some insight to your problem!

Edit - Can't spell "Clusters" apparently lol