【问题标题】:Laravel 5.7 - Undefined offset: 1Laravel 5.7 - 未定义的偏移量:1
【发布时间】:2018-12-12 08:02:11
【问题描述】:

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

categories:id、name(目前为2项)

变体:ID、名称

category_variant:id、category_id、variant_id;

在 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)

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

【问题讨论】:

    标签: php checkbox offset laravel-5.7


    【解决方案1】:

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

    【讨论】:

    • 亲爱的 cbaconnier,非常感谢您的回答。它工作正常。迪米
    猜你喜欢
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 2011-07-22
    • 2018-07-27
    • 2018-10-05
    • 1970-01-01
    相关资源
    最近更新 更多