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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?