Setting selected option in laravel form

2020-05-20 05:01发布

I need to give selected value like this html:

<select name="myselect" id="myselect">
 <option value="1">Item 1</option>
 <option value="2" selected='selected'>Item 2</option>

how can I achieve this, with laravel forms?

12条回答
叼着烟拽天下
2楼-- · 2020-05-20 05:47
            @foreach ($categories as $category)
             <option value="{{$category->id}}" 
               @foreach ($posts->postRelateToCategory as $Postcategory)
                 @if ($Postcategory->id == $category->id)
                 {{'selected="selected"'}}
                 @endif 
               @endforeach >
              {{ $category->category_name }} </option>               
            @endforeach    
查看更多
走好不送
3楼-- · 2020-05-20 05:47

If you have an Eloquent Relationship between your models you can do something like that:

@foreach ($ships as  $ship)
<select name="data[]" class="form-control" multiple>
    @foreach ($goods_containers as  $container)
        <option value="{{ $container->id }}"
                @if ($ship->containers->contains('container_id',$container->id ) ))
                selected="selected"
                @endif
        >{{ $container->number}}</option>
    @endforeach
</select>
@endforeach
查看更多
萌系小妹纸
4楼-- · 2020-05-20 05:48

You have to set the default option by passing a third argument.

{{ Form::select('myselect', [1, 2], 2, ['id' => 'myselect']) }}

You can read the documentation here.

查看更多
男人必须洒脱
5楼-- · 2020-05-20 05:50

Another ordinary simple way this is good if there are few options in select box

<select name="job_status">
   <option {{old('job_status',$profile->job_status)=="unemployed"? 'selected':''}}  value="unemployed">Unemployed</option>
   <option {{old('job_status',$profile->job_status)=="employed"? 'selected':''}} value="employed">Employed</option>
</select>
查看更多
神经病院院长
6楼-- · 2020-05-20 05:54
  <?php
      $items = DB::table('course')->get()->pluck('name','id');
      $selectID = 3;
  ?>

  <div class="form-group">
   {{ Form::label('course_title', 'Course Title') }}
   {!! Form::select('myselect', $items, $select, ['class' => 'form-control']) !!}
  </div>

This show similar types of following options :

<select name="myselect" id="myselect">
 <option value="1">Computer Introduction</option>
 <option value="2">Machine Learning</option>
 <option value="3" selected='selected'>Python Programming</option>
 <option value="4">Networking Fundamentals</option>
 .
 .
 .
 .  
</select>
查看更多
Animai°情兽
7楼-- · 2020-05-20 05:56

You can do it like this.

<select class="form-control" name="resoureceName">

  <option>Select Item</option>

  @foreach ($items as $item)
    <option value="{{ $item->id }}" {{ ( $item->id == $existingRecordId) ? 'selected' : '' }}> {{ $item->name }} </option>
  @endforeach    </select>
查看更多
登录 后发表回答