属性 [vegan] 在此 collection 实例上不存在。 Laravel
Property [vegan] does not exist on this collection instance. Laravel
我正在尝试根据我的 table 中的特定列是 1 还是 0 来显示标题。在我的控制器中,我有(删除了一些不相关的代码):
public function show(Company $id){
$vegan = Company::find($id);
$vegetarian = Company::find($id);
return view('allProducts')->with([
'vegan' => $vegan,
'vegetarian' => $vegetarian,
]);
}
在我看来:
@if($vegan->vegan == 1)
<h3 class="text-center">Vegan</h3>
@endif
但是我收到错误消息
ErrorException (E_ERROR)
Property [vegan] does not exist on this collection instance. (View: C:\xampp\htdocs\EdenBeauty\resources\views\allProducts.blade.php)
我尝试了以下方法,但每次都出现错误:
@if($vegan[0]->vegan == 1)
这给出了未定义的偏移错误
问题是您在查询后遗漏了 first()
:
$vegan = Company::find($id)->first();
$vegetarian = Company::find($id)->first();
在这一行中,您通过 URL 参数将 Company
注入到 show
方法中:
public function show(Company $id){ ... }
此时,$id
是 Company
实例或 null
。调用 $vegan = Company::find($id)
没有任何意义,我真的很惊讶你在代码中的那个点没有出错。
此外,如果您使用注入,请正确命名变量Company $company
以避免混淆,稍后参考:
public function show(Company $company){
$vegan = $company;
$vegetarian = $company;
// Or `$vegan = Company::find($company->id);`
// (This is redundant, but demonstrates the syntax)
return view("...")->with(...);
}
或者,删除注入和查询:
public function show($id){
$vegan = Company::find($id); // Note can use use `firstOrFail()`, etc.
$vegetarian = Company::find($id);
...
}
不管怎样,find()
不会 return 一个 Collection
,所以 $vegan->vegan
不会 return "Property [vegan] does not exist on this collection instance.",但是关于你的一些东西用法就是这样对待它。
我正在尝试根据我的 table 中的特定列是 1 还是 0 来显示标题。在我的控制器中,我有(删除了一些不相关的代码):
public function show(Company $id){
$vegan = Company::find($id);
$vegetarian = Company::find($id);
return view('allProducts')->with([
'vegan' => $vegan,
'vegetarian' => $vegetarian,
]);
}
在我看来:
@if($vegan->vegan == 1)
<h3 class="text-center">Vegan</h3>
@endif
但是我收到错误消息
ErrorException (E_ERROR)
Property [vegan] does not exist on this collection instance. (View: C:\xampp\htdocs\EdenBeauty\resources\views\allProducts.blade.php)
我尝试了以下方法,但每次都出现错误:
@if($vegan[0]->vegan == 1)
这给出了未定义的偏移错误
问题是您在查询后遗漏了 first()
:
$vegan = Company::find($id)->first();
$vegetarian = Company::find($id)->first();
在这一行中,您通过 URL 参数将 Company
注入到 show
方法中:
public function show(Company $id){ ... }
此时,$id
是 Company
实例或 null
。调用 $vegan = Company::find($id)
没有任何意义,我真的很惊讶你在代码中的那个点没有出错。
此外,如果您使用注入,请正确命名变量Company $company
以避免混淆,稍后参考:
public function show(Company $company){
$vegan = $company;
$vegetarian = $company;
// Or `$vegan = Company::find($company->id);`
// (This is redundant, but demonstrates the syntax)
return view("...")->with(...);
}
或者,删除注入和查询:
public function show($id){
$vegan = Company::find($id); // Note can use use `firstOrFail()`, etc.
$vegetarian = Company::find($id);
...
}
不管怎样,find()
不会 return 一个 Collection
,所以 $vegan->vegan
不会 return "Property [vegan] does not exist on this collection instance.",但是关于你的一些东西用法就是这样对待它。