Skip to content

Instantly share code, notes, and snippets.

@mcgwier
Created March 12, 2015 15:15
Show Gist options
  • Save mcgwier/404da53bf2aa89d371ef to your computer and use it in GitHub Desktop.
Save mcgwier/404da53bf2aa89d371ef to your computer and use it in GitHub Desktop.
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) }}
// MISC OPTIONS:
// List of all categories with same parent category
$parent = 'Parent Category Name';
Category::where('parent','=','$parent')->lists('name','id'));
// 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... ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment