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

No comments yet…

Like our articles?

Become a Premium Member for $129/year or $29/month

Written by