63

I want to create a select box like the one below using illuminate\html :

<select>
    <option value="$item->id">$item->name</option>
    <option value="$item->id">$item->name</option>
</select>

In my controller I tried this:

public function create()
{
    $items = Items::all(['id', 'name']);

    return view('prices.create', compact('id', 'items'));
}

And in my view this:

<div class="form-group">
    {!! Form::Label('item', 'Item:') !!}
    {!! Form::select('item_id', $items, null, ['class' => 'form-control']) !!}
</div>

The issue is that instead of $item->name is displaying all the info of the entity.

borracciaBlu
  • 4,017
  • 3
  • 33
  • 41

15 Answers15

106

Laravel provides a Query Builder with lists() function

In your case, you can replace your code

$items = Items::all(['id', 'name']);

with

$items = Items::lists('name', 'id');

Also, you can chain it with other Query Builder as well.

$items = Items::where('active', true)->orderBy('name')->lists('name', 'id');

source: http://laravel.com/docs/5.0/queries#selects


Update for Laravel 5.2

Thank you very much @jarry. As you mentioned, the function for Laravel 5.2 should be

$items = Items::pluck('name', 'id');

or

$items = Items::where('active', true)->orderBy('name')->pluck('name', 'id');

ref: https://laravel.com/docs/5.2/upgrade#upgrade-5.2.0 -- look at Deprecations lists

mininoz
  • 5,908
  • 4
  • 23
  • 23
  • 6
    since 5.2 `lists` is deprecated in favor of `pluck`. in your example it would be `Items::all(['id', 'name'])->pluck('name', 'id');` – Jarry Mar 05 '16 at 16:41
  • 2
    Mininoz, how can I show up select box in blade without using `Form` class, e.g. `@foreach($items as $items_each)@endforeach` – horse Feb 25 '17 at 18:34
  • 1
    Hi, i'm using your code on laravel 5.5 and it's saying 'trying to get property of non-object'. Is compact needed? – Gabriel Augusto Dec 23 '17 at 14:49
31

Just change your controller to the following:

public function create()
{
    $items = Subject::all(['id', 'name']);
    return View::make('your view', compact('items));
}

And your view to:

<div class="form-group">
  {!! Form::Label('item', 'Item:') !!}
  <select class="form-control" name="item_id">
    @foreach($items as $item)
      <option value="{{$item->id}}">{{$item->name}}</option>
    @endforeach
  </select>
</div>

Hope this will solve your problem

Sohel0415
  • 9,523
  • 21
  • 30
29

Laravel >= 5.3 method lists() is deprecated use pluck()

$items = Items::pluck('name', 'id');

{!! Form::select('items', $items, null, ['class' => 'some_css_class']) !!}

This will give you a select box with same select options as id numbers in DB

for example if you have this in your DB table:

id name
1  item1
2  item2
3  item3
4  item4

in select box it will be like this

<select>
<option value="1">item1</option>
<option value="2">item2</option>
<option value="3">item3</option>
<option value="4">item4</option>
</select>

I found out that pluck now returns a collection, and you need to add ->toArray() at the end of pluck...so like this: pluck('name', 'id')->toArray();

lewis4u
  • 14,256
  • 18
  • 107
  • 148
  • What if we don't use Form class? `@foreach($elements as $element_each)@endforeach` gives error. – horse Feb 25 '17 at 18:22
  • If you use form class you have to install the facade. It doesn't work without it. Google for laravel form collective – lewis4u Feb 25 '17 at 18:26
  • horse try changing `{!! !!}` with `{{ }}` – lewis4u Feb 27 '17 at 08:01
8

Controller

 $campaignStatus = Campaign::lists('status', 'id');

compact('campaignStatus') will result in [id=>status]; //example [1 => 'pending']

return view('management.campaign.index', compact('campaignStatus'));

View

{!! Form::select('status', $campaignStatus, array('class' => 'form-control')) !!}
Hashmat Waziri
  • 476
  • 9
  • 9
  • 3
    WIth this expression class -> form-control does not work. Naing Win answer with {!! Form::select('item_id', $items, null, ['class' => 'form-control']) !!} works – Mindau Apr 20 '16 at 23:39
6

Laravel use array for Form::select. So I passed array like below:

$datas = Items::lists('name', 'id');
$items = array();

foreach ($datas as $data)
{
    $items[$data->id] = $data->name;
}

return \View::make('your view', compact('items',$items));

In your view:

<div class="form-group">
    {!! Form::label('item', 'Item:') !!}
    {!! Form::select('item_id', $items, null, ['class' => 'form-control']) !!}
</div>
Naing Win
  • 1,236
  • 1
  • 8
  • 7
6

In your controller, add,

public function create()
{
    $items = array(
        'itemlist' =>  DB::table('itemtable')->get()
      );

    return view('prices.create', $items);
}

And in your view, use

<select name="categories" id="categories" class="form-control">
  @foreach($itemlist as $item)
    <option value="{{ $item->id }}">{{ $item->name }}</option>
  @endforeach
</select>

In select box, it will be like this,

<select>
 <option value="1">item1</option>
 <option value="2">item2</option>
 <option value="3">item3</option>
 ...
</select>
itzmebibin
  • 9,199
  • 8
  • 48
  • 62
6

I have added toArray() after pluck

$items = Item::pluck('name', 'id')->toArray();

{{ Form::select('item_id', [null=>'Please Select'] + $items) }}
Anjani Barnwal
  • 1,362
  • 1
  • 17
  • 23
Gediminas Šukys
  • 7,101
  • 7
  • 46
  • 59
4

Laravel 5.3 use pluck($value, $key )

$value is displayed in your drop list and $key is id

controller

$products = Product::pluck('name', 'id');

return view('main.index', compact('products'));

view

{{ Form::select('id', $products, null, ['class' => 'form-control']) }}
kipzes
  • 694
  • 2
  • 10
  • 27
Gaetano
  • 39
  • 2
  • 1
    You should really add some explanation as to why this should work - you can also add code as well as the comments in the code itself - in its current form, it does not provide any explanation which can help the rest of the community to understand what you did to solve/answer the question. This is especially important for an older question and the questions that already have answers. You should also make some effort to correctly format the code in your post. – ishmaelMakitla Jan 14 '17 at 17:44
3

Laravel 5.*

In your controller:

$items= Items::pluck('name', 'id')->toArray();
return view('your view', compact('items', $items));

In your view:

{{ Form::select('organization_id', $items, null, []) }}
Dominic Tan
  • 101
  • 3
3

Sorry for the late reply

Obviously lists method has been deprecated in Laravel, but you can use the pluck method.

For Eg:

Laravel 5.7

public function create()
{
    $countries =  Country::pluck('country_name','id');
    return View::make('test.new')->with('countries', $countries);
}

and in the view if you are FORM components just pass as

{{  Form::select('testname',$countries,null,['class' => 'required form-control select2','id'=>'testname']) }}

if will generate the dropdown

but i have a situation to show that select country as the first option and as null value

<option value="" selected="selected">--Select  Country--</option>

so I have referred to

https://stackoverflow.com/a/51324218/8487424

and fixed this, but in later times if I want to change this I hate being changing it in the view

So have created the helper function based on https://stackoverflow.com/a/51324218/8487424 and placed in the Country Model

public static  function toDropDown($tableName='',$nameField='',$idField='',$defaultNullText='--Select--')
{
    if ($idField == null)
    {
        $idField="id";
    }

    $listFiledValues = DB::table($tableName)->select($idField,$nameField)->get();

            $selectArray=[];
            $selectArray[null] = $defaultNullText;
            foreach ($listFiledValues as $listFiledValue) 
            {
                $selectArray[$listFiledValue->$idField] = $listFiledValue->$nameField;
            }
            return $selectArray;
        }

and in controller

public function create()
    {
      $countries = Country::toDropDown('countries','name','id','--Select  Country--');
      return View::make('test.new')->with('countries', $countries);
    }

and finally in the view

 {{  Form::select('testname',$countries,null,['class' => 'required form-control select2','id'=>'testname']) }}

and the result is as expected, but I strongly recommend to use pluck() method

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
ManojKiran A
  • 5,896
  • 4
  • 30
  • 43
2

For Laravel 5 :

$items = Items::lists('name', 'id');

Push an item onto the beginning of the collection.

$items->prepend($value, $key = null);
3ehrang
  • 619
  • 1
  • 7
  • 22
2

To populate the drop-down select box in laravel we have to follow the below steps.

From controller we have to get the value like this:

 public function addCustomerLoyaltyCardDetails(){
        $loyalityCardMaster = DB::table('loyality_cards')->pluck('loyality_card_id', 'loyalityCardNumber');
        return view('admin.AddCustomerLoyaltyCardScreen')->with('loyalityCardMaster',$loyalityCardMaster);
    }

And the same we can display in view:

 <select class="form-control" id="loyalityCardNumber" name="loyalityCardNumber" >
       @foreach ($loyalityCardMaster as $id => $name)                                     
            <option value="{{$name}}">{{$id}}</option>
       @endforeach
 </select>

This key value in drop down you can use as per your requirement. Hope it may help someone.

  • Why not just reverse the ```@foreach ($loyalityCardMaster as $id => $name) ``` this way ```@foreach ($loyalityCardMaster as $name => $id)```? With this, ```$id``` has real id value and so for the ```$name``` – Hooman Limouee Apr 24 '22 at 04:27
0

Try this one. Without using controller

{{ Form::select('apartment_id', \App\Apartment::all()->pluck('apartment_name', 'apartment_id')->toArray(), null,['class'=>'select2 form-control', 'multiple'=>'multiple','required','id' => 'apartment_id']) }}
ManojKiran A
  • 5,896
  • 4
  • 30
  • 43
Vinayak
  • 9
  • 2
  • 4
    Why should the OP "try this one"? A **good answer** will always have an explanation of what was done and why it was done in such a manner, not only for the OP but for future visitors to SO. – B001ᛦ Jan 27 '17 at 09:30
  • It's against MVC pattern, you shouldn't access database in your views. – Hooman Limouee Apr 24 '22 at 04:15
0

Many has been said already but keep in mind that there are a times where u don't want to output all the records from the database into your select input field ..... Key example I have been working on this school management site where I have to output all the noticeboard categories in a select statement. From my controller this is the code I wrote

Noticeboard:: groupBy()->pluck('category')->get();

This way u get distinct record as they have been grouped so no repetition of records

Dawood Iddris
  • 121
  • 1
  • 4
0

I was trying to do the same thing in Laravel 5.8 and got an error about calling pluck statically. For my solution I used the following. The collection clearly was called todoStatuses.

<div class="row mb-2">
    <label for="status" class="mr-2">Status:</label>
    {{ Form::select('status', 
                $todoStatuses->pluck('status', 'id'), 
                null, 
                ['placeholder' => 'Status']) }}
</div>
PhPGuy
  • 41
  • 3