douxun2018 2018-12-12 08:02
浏览 157
已采纳

Laravel 5.7 - 未定义的偏移量:1

I'm new in Laravel and it is my first question. I have 3 tables:

categories: id, name (at the moment 2 items)

variants: id, name

category_variant: id, category_id, variant_id; <-- Every variant has 1 or 2 categories

In the VariantController I have following code:

public function edit($id)
{
    $variant = Variant::where('id', $id)->with('categories')->first();
    $categories = Category::all();

    return view('admin.variant.edit', compact('variant', 'categories'));
}

In the edit.blade.php I have following html:

@foreach ($categories as $key=>$category)
   <div class="form-group form-float">
   @if (isset($variant->categories[$key]->pivot->category_id)) <-- I think here is the problem
      <input type="checkbox" id="wb" class="filled-in" name="wb" value="{{$category->id}}" {{ $category->id == $variant->categories[$key]->pivot->category_id  ? 'checked' : ''}} >
      <label for="wb">{{ $category->name}}</label>
   @else
      <input type="checkbox" id="wb" class="filled-in" name="wb" value="{{$category->id}}">
      <label for="wb">{{ $category->name}}</label>
   @endif
   </div>
@endforeach

I want to know which category was checked in the checkbox. If the variant has all 2 categories everthing is ok but if the user has chosen only one category I get an error

Undefined offset: 1 (View: /shui/resources/views/admin/variant/edit.blade.php)

How can I solve this problem? Thanks in advance Dimi

</div>
  • 写回答

1条回答 默认 最新

  • dqellle310167 2018-12-12 09:07
    关注

    You can use the power of collection:

    @if($variant->categories->contains($category))
        {{--  You does not need to test a second time to know if you need to "check" --}}
        <input type="checkbox" id="wb" class="filled-in" name="wb" value="{{$category->id}}" checked >
        <label for="wb">{{ $category->name}}</label>
    @else
        {{-- Do stuff --}}
    @endif
    

    Or simpler. Remove the first @if

    <input type="checkbox" id="wb" class="filled-in" name="wb" value="{{$category->id}}" $variant->categories->contains($category)? 'checked' : '' >
    <label for="wb">{{ $category->name}}</label>
    

    Also in you Controller, you can simplify

    $variant = Variant::where('id', $id)->with('categories')->first();
    

    with

    $variant = Variant::with('categories')->find($id);
    // Or better, Laravel throws a 404 error when the id doesn't exists
    $variant = Variant::with('categories')->findOrFail($id);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 混合键合键合机对准标识
  • ¥100 现在不懂的是如何将当前的相机中的照片,作为纹理贴图,映射到扫描出的模型上
  • ¥15 目标跟踪,计算机视觉
  • ¥15 魔霸ROG7 pro,win11.息屏后会显示黑屏,如图,如何解决?(关键词-重新启动)
  • ¥15 有没有人知道这是哪里出了问题啊?要怎么改呀?
  • ¥200 C++表格文件处理-悬赏
  • ¥15 Windows Server2016本地登录失败
  • ¥15 复合卡卡号轨道写入芯片卡
  • ¥20 基于MATLAB的TDOA
  • ¥15 为啥输入字体突然变了