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

报告相同问题?

悬赏问题

  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接
  • ¥15 MATLAB中使用parfor,矩阵Removal的有效索引在parfor循环中受限制
  • ¥20 Win 10 LTSC 1809版本如何无损提升到20H1版本
  • ¥50 win10 LTSC 虚拟键盘不弹出
  • ¥30 微信小程序请求失败,网页能正常带锁访问
  • ¥15 Matlab求解微分方程,如何用fish2d进行预优?