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

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

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


                        
    
提交评论

  • 2020-11-29 21:33

    I have added toArray() after pluck

    $items = Item::get()->pluck('name', 'id')->toArray();
    
    {{ Form::select('item_id', [null=>'Please Select'] + $items) }}
    
    0 讨论(0)
  • 2020-11-29 21:34

    For Laravel 5 :

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

    Push an item onto the beginning of the collection.

    $items->prepend($value, $key = null);
    
    0 讨论(0)
  • 2020-11-29 21:34

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

    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.

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

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