Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel database select dropdown with placeholder

Hi I'm populating a select dropdown with clients that exist in my database, however I want a placeholder first e.g. Please select a Client. Does anyone know the syntax?

This is what I have so far:

@if(count($client_options)>0)

    {{ Form::select('client', $client_options , Input::old('client'), array('placeholder' => 'Please select a client', 'id' => 'select_client', 'class' => 'chosen-select select', 'tabindex' => '2', )) }}

@endif 

The placeholder attribute but that doesn't work, does anyone know how? Thanks in advance

like image 598
GSG Avatar asked Mar 20 '26 08:03

GSG


1 Answers

Assume that you are creating a dropdown list in Laravel form builder. Then the code should be like this -

In controller -

$categories = Category::select('id', 'name')->lists('name', 'id')->prepend('Select a category', '')->toArray();

and in view -

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

Tested with Laravel 5.x.

Or if you have an array like -

$array = ['1' => 'lorem ipsum', '4' => 'Another text'];

And after passing this array to view -

{!! Form::select('cat_id', $array, old('cat_id')) !!}

There will be no placeholder. If you pass below array -

$array = ['' => 'Select category', '1' => 'lorem ipsum category', '4' => 'Another category'];

or there is a collection which you want to pass in view to build select/dropdown list then

$array = $collection->prepend('Select a category', '')->toArray();

You need to pass an array in order to build the dropdown list.

Note: array_unshift or array_merge will not work as expected!

like image 81
HADI Avatar answered Mar 22 '26 21:03

HADI