Laravel 5.7-未定义偏移量:1

时间:2018-12-12 08:02:11

标签: php checkbox offset laravel-5.7

我是Laravel的新手,这是我的第一个问题。 我有3张桌子:

类别:ID,名称(目前有2个项目)

变体:ID,名称

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)

如何解决此问题? 提前致谢 迪米

1 个答案:

答案 0 :(得分:0)

您可以使用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);