Laravel 5.1: empty option in Form::select with lists()

There is one small upgrade in Laravel 5.1 which breaks apps with earlier versions – it is related to <select> dropdown items. For a long time, Eloquent had a useful way of passing options to Form::select() – but adding an empty parameter doesn’t work in Laravel 5.1 anymore. Here’s what to do:

So, in short, the old method (maybe you didn’t even know it):

ProductController.php:

$categories = [''=>''] + Category::lists('name', 'id');
return view('products.create', compact('categories'));

It would return $categories as array, adding the first option as empty and then it can be used in a View:

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

So that’s the old convenient way which worked up to Laravel 5.0. If you try to use it in Laravel 5.1, you will get such error:

0702_laravel_unsupported_types

The reason is that in 5.0 version function lists() returned an array, which then could be added to another array with a simple + symbol. In 5.1 $categories is a Collection Object:

Illuminate\Support\Collection Object ( [items:protected] => Array ( [1] => Shirts [2] => Coats [3] => Dresses ) )

The solution is simple – to convert it back to Array, just using a function all() at the end:

$categories = [''=>''] + Category::lists('name', 'id')->all();

This way you will get your form as before 5.1 version. Here’s what the official upgrade documentation says:

0702_laravel_eloquent_lists

Like our articles?
Check out our Laravel online courses!

10 COMMENTS

  1. How about this construct:

    [”=>”] + Category::lists(‘name’, ‘id’);

    I see this for the first time. What this part mean? [”=>”] +

    Thanks.

    • Practivcally this can be used as a placeholder on a select box. So instead of
      [”=>”] + Category::lists(‘name’, ‘id’);
      you can do this:
      [”=>’–Select a Category’] + Category::lists(‘name’, ‘id’);

  2. And if you only have an array with the values and you would like them to be the labels too, you can do:

    Form::select(‘size’, array_combine($sizes = [‘L’, ‘XL’], $sizes));

  3. Hi Povilas Korop
    I also meet this problem same as you.Now i have solve it by convert it to array.

    {!! Form::select(‘company_id’, [” => ‘Select Company’] + $companies->toArray() ,null , array(‘class’ => ‘form-control’)) !!}

  4. “Lists” method return an Illuminate\Database\Eloquent\Collection object which extends BaseCollection which has a “prepend” method. A proper way to add the empty value would be to use this method :

    $customers = Customer::all([‘first_name’,’last_name’,’id’])->lists(‘fullname’, ‘id’);
    $customers->prepend(”,”);

    That way, you don’t have to convert your Collection to an array!

LEAVE A REPLY

Please enter your comment!
Please enter your name here