Following the development standards, do so:
In your Item model, 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
$optional
parameter of this method is just to set whether to have a default (non-value) option in your Grouped List , for example: Select an item .
- After this there is only one check if it has been informed or not, otherwise returns only the list of elements
Note:
If you wanted to add a condition in 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 scope defined in the model (this is an 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');
}