Creating dynamic select dropdown list with laravel 5.1

Posted on
Creating dynamic select dropdown list with laravel 5.1

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 = ['' =--> 'Select a Category'] + Category::lists('name', 'id')->all();

This assumes you have id and name columns in your categories table. Then you just need to pass $categories to your view:

return view('post.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. Please comment, share, and like if you can, thanks!


Comment ( 1 )

  1. ReplyA WordPress Commenter
    Hi, this is a comment. To get started with moderating, editing, and deleting comments, please visit the Comments screen in the dashboard. Commenter avatars come from Gravatar.