Simple Dropdown list from Eloquent List Method Laravel 5.1

Access all tutorials in sprocket icon.

October 4, 2015 from author Bill Keck.

Laravel makes creating a dynamic dropdown list incredibly simple. Let’s say for example, you have a Category model, which holds the categories you want to use in a dropdown list. You can just use the lists method pull out the values you want for the dropdown list:



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

This assumes you have id and category_name columns in your categories table. Obviously if you are just calling it ‘name’, then use that.

Then you just need to pass $categories to your view:



return view('yourview.create', compact('categories'));

That returns an array with the values you need, which you can just pop into your dropdown list in your view. I’m using the Collective Form Helper package for my select:



{!! Form::select('category_id', $categories) !!}

And that’s it, you get your dropdown list. Little helpers like this make Laravel a pleasure to work with.

I hope you have enjoyed this tutorial and found it useful. Click on the sprocket icon at the top of the page to see all tutorials. Please comment, share, and like if you can, thanks!

I don’t have a donate button, but If you would like to support my work and learn more about Laravel, you can do so by buying one of my books, Laraboot: laravel 5* For Beginners, I really appreciate it.