3/12/2015 - 3:15 PM

Laravel: Easy dropdowns with Eloquent's Lists method

Laravel: Easy dropdowns with Eloquent's Lists method

// Many of you may know this already, but for those who don't this is really handy for building dropdowns

// Suppose you want to show a categories dropdown whose information is pulled from an Eloquent model
// You can use the query builder's "lists" method (available for Eloquent as any query builder method) which
// returns an associative array you can pass to the Form::select method

$categories = Category::lists('title', 'id');

// note that the parameters you pass to lists correspond to the columns for the value and id, respectively
// in this case, "title" and "id"

// you should pass this data to your view and then build the dropdown inside it

//somewhere in your view
{{ Form::select('category', $categories) }}


// List of all categories with same parent category
$parent = 'Parent Category Name';

// Where clause
$categories = Category::where('isActive', 1)->lists('title', 'id');

// Null option for first item
$categories = ['' => ''] + Category::lists('title', 'id');
// Results in ['' => '', 1 => 'First Category', 2 => 'Second Category', etc... ]