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

Laravel 5.7 - Undefined offset: 1

我是 Laravel 的新人,这是我的第一个问题。 我有 3 个表:

类别:id、姓名(目前有 2 项)

变体:id、name

category_variant:id,category_id,variant_id; <-- 每个变体都有 1 或 2 个类别

在 VariantController 中,我有以下代码:

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

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

在 edit.blade.php 我有以下 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

我想知道在复选框中选中了哪个类别。如果变体具有所有 2 个类别,一切正常,但如果用户只选择了一个类别,我会收到错误消息

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

我该如何解决这个问题? 提前致谢 迪米

你可以使用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

或者更简单。删除第一个 @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>

同样在你的Controller中,你可以简化

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

$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);