我必须在创建产品表单选择列表中显示品牌名称,其中品牌名称来自品牌模型,但是当我查看创建产品表单时会发生此错误
试图获取非对象的属性“ id”(查看:C:\ xampp \ htdocs \ MobileShop \ resources \ views \ admin \ product \ createProduct.blade.php
我的品牌模特是:
class brand extends Model
{
protected $connection = 'mysql';
protected $primaryKey = 'id';
protected $fillable = ['brandName'];
public $timestamps = false;
public function product(){
return $this->hasMany('App\Product');
}
protected $table = 'brands';
}
我的产品型号是
class Product extends Model
{
protected $connection = 'mysql';
protected $table = 'products';
protected $primaryKey = 'id';
public $timestamps = false;
protected $fillable =
['productName','brand_id','description','price','image'];
public function brand(){
$this->belongsTo('App/brand');
}
}
ProductController创建方法
enter public function create()
{
$product = brand::pluck('brandName','id');
return view('admin.product.createProduct',compact('product'));
}
我的createProduct刀片视图文件是
<form class="form-horizontal" method="POST" action="{{url('/product')}}" enctype="multipart/form-data" >
{{csrf_field()}}
<div class="form-group">
<label for="name" class="col-md-4 control-label">Product Name :</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control" name="name" required autofocus>
</div>
</div>
<div class="form-group">
<label for="name" class="col-md-4 control-label">Brand:</label>
<div class="col-md-6">
<select name="cars" class="form-control" >
@foreach($product as $item)
<option value="{{$item->id}}"> #-->this line error occure#
{{$item->brandName}}
</option>
@endforeach
</select>
</div>
</div>
<div class="form-group">
<label for="description" class="col-md-4 control-label">Description :</label>
<div class="col-md-6">
<textarea name="description" id="description" class="form-control" ></textarea>
</div>
</div>
<div class="form-group">
<label for="price" class="col-md-4 control-label">Price :</label>
<div class="col-md-6">
<input id="price" type="text" class="form-control" name="price" required autofocus>
</div>
</div>
答案 0 :(得分:1)
Try this
{{Form::select('cars', $product, ['class' => 'form-control'])}}
Instead of
<select name="cars" class="form-control" >
@foreach($product as $item)
<option value="{{$item->id}}"> #-->this line error occure#
{{$item->brandName}}</option>
@endforeach
</select>
Otherwise get all data instead of pluck
$product = brand::all();
答案 1 :(得分:0)
将第二个参数传递给pluck
意味着您拥有一个key => value
数组(brandName
是值,id
是键)。
所以$product = brand::pluck('brandName','id');
会给你一个像这样的数组:
['id1' => 'brandName1', 'id2' => 'brandName2']
因此,在模板中,您应该以这种方式进行迭代:
@foreach($product as $id => $name)
{{ $id }} - {{ $name }}
@endforeach