【发布时间】:2023-03-15 22:27:01
【问题描述】:
我试图根据表中的特定列是 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)
这会产生未定义的偏移误差
【问题讨论】:
-
作为一个指针,你调用 db 两次效率很低,
$vegan = Company::find($id);与$vegetarian相同 - 你最好命名变量$company并且只做查询一次:) -
如果确实需要这些变量进行填充,可以使用findOrFail,而不是find only。如果 Id 不存在,它会抛出一个状态为 404 的错误。在你的路由文件中更深入会很有趣。
-
另外,Company 的主键是什么?如果 ID 存在于表 Company 中,请尝试执行
Comany::where('id', $id)->firstOrFail();
标签: php laravel eloquent laravel-5.8