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.

5 thoughts on “Simple Dropdown list from Eloquent List Method Laravel 5.1

  1. leandro says:

    Na hora de inserir no banco de dados nem todos os a id são mandados corretamente. ex(tem o id=1 e o id=2)cando eu mando para o banco de dados o que tem o id=1 vai como zero mais quando eu mando o id=2, ele vai corretamente.
    Como eu faço para corrigir isso e mandar todos corretamente.


    • Without knowing the real problem, and without speaking Spanish, it may be that you are confusing the index with the key. Sorry, can’t help much more than that…


      • @leandro Says that,
        At the time of inserting in the database not all the id are sent correctly. Ex (has id = 1 and id = 2) When I send to the database what has id = 1 goes to zero more when I send id = 2, it goes correctly.
        How do I correct this and send them all correctly.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s