Laravel Dynamic Checkbox error: Trying to get property 'id' of non-object
Laravel Dynamic Checkbox error: Trying to get property 'id' of non-object
我想要达到的目标:
用户可以为一个产品分配多个超市,也可以为多个产品分配多个超市。注册产品时,我希望用户能够 select 从数据库中填充的复选框。
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
解释评论中所说的内容:
您没有在 $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
我想要达到的目标: 用户可以为一个产品分配多个超市,也可以为多个产品分配多个超市。注册产品时,我希望用户能够 select 从数据库中填充的复选框。
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
解释评论中所说的内容:
您没有在 $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