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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里