Recently I realised I’ve been doing the wrong way to populate the array for Form::select().
In order to get Form::select() to work, the array you parse in must contain key => value. So in the past, I’ve been doing it this way:
$select_array = array(); foreach (Classname::all() as $model) { $select_array[$model->id] = $model->name; }
It does the work, but there’s a built-in function in Laravel that can do this (probably faster, I think) in just 1 line:
$select_array = Classname::lists('name', 'id');
It returns an array that will work with Form::select().
This function is mentioned in the Laravel Documentation to retrieve specific column from a model. But it wasn’t clear that it’s also useful to populate an array for Form::select().
Advanced level
What if the value you want to get is in another class that’s related to this class? Well, we can combine join() with select() and then list().
For example:
$select_array = ModelOne::join('modeltwos', 'modeltwos.id', '=', 'modelones.modeltwo_id') ->select('modeltwos.name', 'modelones.id') ->lists('name', 'id');
I hope this is useful. Do leave a comment if you have a better way of populating the array for Form::select().