我尝试根据表中的特定列是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)这会产生未定义的偏移错误
发布于 2019-10-04 21:34:41
问题是您在查询之后遗漏了first():
$vegan = Company::find($id)->first();
$vegetarian = Company::find($id)->first();发布于 2019-10-04 22:35:02
在这一行中,您将通过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()都不会返回Collection,因此$vegan->vegan不会返回“属性素食不存在于此集合实例上。”,但您的用法是这样对待它的。
https://stackoverflow.com/questions/58237447
复制相似问题