Undefined offset: 2 in Laravel 5

2019-09-25 11:02发布

I want to keep the values in multiselect however, it shows Undefined offset: 2. The codes is below for the blade file.

<select multiple="multiple" name="warehouseId[]" id="warehouse" class="form-control" style="width:100%;">
@if($warehouseData)
  @foreach ($warehouseData as $key => $warehouse)
    <option value="{{$warehouse->id}}" >{{$warehouse->name}} {{$adminUserWarehouseSelectedData[$key]->id}}</option>
  @endforeach
@endif
</select>

2条回答
小情绪 Triste *
2楼-- · 2019-09-25 11:15

I think the answer you have accepted here is not 100% right. You have multiple data in $adminUserWarehouseSelectedData coming from controllers. As you have used multiple select here I assumed that.

So this is the proper way to do it.

<select multiple="multiple" name="warehouseId[]" id="warehouse" class="form-control" style="width:100%;">
@if($warehouseData)
  @foreach ($warehouseData as $key => $warehouse)
    <option value="{{$warehouse->id}}" >{{$warehouse->name}} @foreach($adminUserWarehouseSelectedData as $data) $data->id  @endforeach {{$warehouse->name}}</option>
            @endforeach</option>
  @endforeach
@endif
</select>

I know that you are not using this code but for other users correct answer is the most preferable answer.

查看更多
贪生不怕死
3楼-- · 2019-09-25 11:25

Add an @isset directive

<select multiple="multiple" name="warehouseId[]" id="warehouse" class="form-control" style="width:100%;">
   @if($warehouseData)
      @foreach ($warehouseData as $key => $warehouse)
         @isset($adminUserWarehouseSelectedData[$key]->id)
           <option value="{{$warehouse->id}}">
            {{$warehouse->name}} {{$adminUserWarehouseSelectedData[$key]->id}}
           </option>
         @endisset
      @endforeach
  @endif
</select>
查看更多
登录 后发表回答