Laravel-5 how to populate select box from database with id value and name value

后端 未结 15 1740
梦如初夏
梦如初夏 2020-11-29 21:15

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


                        
    
提交评论

  • 2020-11-29 21:23

    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>
    
    0 讨论(0)
  • 2020-11-29 21:24

    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>
    
    0 讨论(0)
  • 2020-11-29 21:24

    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']) }}
    
    0 讨论(0)
  • 2020-11-29 21:26

    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();

    0 讨论(0)
  • 2020-11-29 21:27

    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']) }}
    
    0 讨论(0)
  • 提交回复
    热议问题