Laravel动态复选框错误:试图获取非对象的属性'id'

问题描述 投票:-1回答:1

我想要达到的目标:用户可以将多个超市分配给一个产品,并且可以将超市分配给多个产品。注册产品时,我希望用户能够从数据库中填充的复选框中进行选择。

Product.php

class Product extends Model
{
    //
    protected $fillable = [
        'name',
        'summary',
        'category_id',
        'author_id',
        'supermarket_id',
        'gf_rank_id',
        'average_price',
        'photo_id',
        'online_store_path',
        'ingredients',
    ];

    public function supermarket() {
        return $this->belongsToMany('App\Supermarket');
    }

}

Supermarket.php

class Supermarket extends Model
{
    protected $fillable = [
        'name',
        'url',
    ];

    public function products() {
        return $this->belongsToMany('App\Products');
    }
}

ProductsController.php

  public function create()
    {
        $categories = Category::pluck('name', 'id')->all();
        $supermarkets = Supermarket::pluck('name', 'id')->all();
        return view('admin.products.create', compact(['categories', 'supermarkets']));
    }

create.blade.php

        @foreach ($supermarkets as $supermarket)
        <div class="col-sm-3">
            {!! Form::checkbox('supermarket_id[]', $supermarket->id) !!}
            {!! Form::label('supermarkets', $supermarket) !!}
        </div>
        @endforeach
laravel checkbox laravelcollective
1个回答
0
投票

要解释评论中所说的内容:

因为正在使用$supermarkets,所以没有在pluck('name','id')数据中提供对象。您正在提供一个关联数组:

[ 
    1 => 'supermarket A',
    2 => 'supermarket B'
]

因此您需要将显示代码更改为:

@foreach ($supermarkets as $id => $name)
    <div class="col-sm-3">
        {!! Form::checkbox('supermarket_id[]', $id) !!}
        {!! Form::label('supermarkets', $name) !!}
    </div>
@endforeach
© www.soinside.com 2019 - 2024. All rights reserved.