简体   繁体   English

Laravel 5.7-未定义偏移量:1

[英]Laravel 5.7 - Undefined offset: 1

I'm new in Laravel and it is my first question. 我是Laravel的新手,这是我的第一个问题。 I have 3 tables: 我有3张桌子:

categories: id, name (at the moment 2 items) 类别:ID,名称(目前有2个项目)

variants: id, name 变体:id,名称

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

In the VariantController I have following code: 在VariantController中,我有以下代码:

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

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 如果该变体具有所有2个类别,则一切正常,但是如果用户仅选择一个类别,则会出现错误

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

How can I solve this problem? 我怎么解决这个问题? Thanks in advance Dimi 在此先感谢Dimi

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 删除第一个@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 同样在Controller中,您可以简化

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM