Following the development patterns, do so:
In his model Item create the following method:
/**
* getList method
* Retorna a lista de itens
*
* @access public
* @return Array
* @since 1.0
* @version 1.0
* @author rogersneves
*/
public static function getList($optional = true)
{
if ($optional) {
return array('' => 'Selecione (opcional)') + static::lists('nome', 'id');
} else {
return static::lists('nome', 'id');
}
}
On your controller
$items = Item::getList();
return View::make('sua_view')->with('items', $items);
Explaining:
- The parameter
$optional
of this method is only to define whether you will have a default option (no value) in your Grouped List, for example: Select an item.
- After this there is only one check whether it has been informed or not, otherwise it returns only the list of elements
Obs:
If you wanted to add a condition to this method, just do the following:
return array('' => 'Selecione (opcional)') + static::where('status', 1)->lists('nome', 'id');
Or in my case:
return array('' => 'Selecione (opcional)') + static::active()->lists('name', 'id');
Being active()
a model-defined Scope (this is example only, not applied to your case, or if you wanted, change the name of the fields):
/* ----------------------------------------------------------------------------
| Scopes
| -----------------------------------------------------------------------------
|
| Escopos pré-definidos
|
*/
/**
* scopeActive method
*
* @access public
* @param Array $query
* @return void
*/
public function scopeActive($query)
{
return $query->where('active', 1)->orderBy('name');
}
Have you tried the lists()?
– Iberê
I also use creation through the method
lists('descricao','id')
– Flávio H. Ferreira