Dynamically Populating a Laravel Dropdown Box

  • March 30, 2015

Welcome to the incredibly popular Easy Laravel 5 companion blog. To celebrate the new edition's release (updated for Laravel 5.5!) use the discount code easteregg to receive 20% off the book or book/video package! » Buy the book

Registered PHPLeaks.com users can contribute links to the community via a simple form (see below screenshot). Each link is categorized using one of several predefined links which are retrieved from a table named categories. These categories are retrieved and dynamically populate a form dropdown. So how is this form populated? Read on to learn how.

This form is generated via the Link controller's create action. This action is very simple, and looks like this:

public function create()
    $categories = \DB::table('categories')->lists('name', 'id');
    return view('link.create')->with('categories', $categories);

Thanks to the query builder's lists method, the $categories variable contains an array of category IDs and names. This is useful because a select box requires two values for each select option: a label and value. This variable is passed into the view, and subsequently passed into the Form::select helper, as demonstrated here:

<div class="form-group">
    {!! Form::label('Link Category') !!}<br />
    {!! Form::select('category', 
        (['0' => 'Select a Category'] + $categories), 
            ['class' => 'form-control']) !!}

Notice how a static form label is added to the $categories array. You're not required to do this, but I think it's a touch more user-friendly to include a dropdown prompt. When the helper is rendered to the browser the resulting HTML looks like this:

<select name="category" class="form-control">
    <option value="0">Select a Category</option>
    <option value="1">Laravel</option>
    <option value="2">Zend Framework</option>
    <option value="3">CakePHP</option>
    <option value="4">PHP</option>

Once the form is submitted the associated form request validates the form fields, and if valid, the category is associated with the new link. If you'd like to learn more about how this is accomplished, check out the PHPLeaks project!