[英]Property [vegan] does not exist on this collection instance. Laravel
I'm trying to show a title based on whether a specific column in my table is 1 or 0. In my Controller I have (edited out some irrelevant code):我试图根据表中的特定列是 1 还是 0 来显示标题。在我的 Controller 中,我有(编辑了一些不相关的代码):
public function show(Company $id){
$vegan = Company::find($id);
$vegetarian = Company::find($id);
return view('allProducts')->with([
'vegan' => $vegan,
'vegetarian' => $vegetarian,
]);
}
and in my view:在我看来:
@if($vegan->vegan == 1)
<h3 class="text-center">Vegan</h3>
@endif
However I get error message但是我收到错误消息
ErrorException (E_ERROR)
Property [vegan] does not exist on this collection instance. (View: C:\xampp\htdocs\EdenBeauty\resources\views\allProducts.blade.php)
Ive tried the following but I get errors every time:我尝试了以下方法,但每次都会出错:
@if($vegan[0]->vegan == 1)
This gives undefined offset errors这会产生未定义的偏移误差
The problem is you're missing first()
after your queries:问题是您在查询后丢失了
first()
:
$vegan = Company::find($id)->first();
$vegetarian = Company::find($id)->first();
In this line, you're injecting a Company
into your show
method via URL parameter:在这一行中,您通过 URL 参数将
Company
注入到您的show
方法中:
public function show(Company $id){ ... }
At that point, $id
is either a Company
instance or null
.此时,
$id
是Company
实例或null
。 Calling $vegan = Company::find($id)
doesn't make any sense, and I'm actually surprised you don't get an error at that point in the code.调用
$vegan = Company::find($id)
没有任何意义,实际上我很惊讶您在代码中没有收到错误。
Also, if you're using injection, name the variable correctly Company $company
to avoid confusion, and reference later:此外,如果您使用注入,请正确命名变量
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(...);
}
Alternatively, remove injection and query:或者,删除注入和查询:
public function show($id){
$vegan = Company::find($id); // Note can use use `firstOrFail()`, etc.
$vegetarian = Company::find($id);
...
}
Either way, find()
does not return a Collection
, so $vegan->vegan
would not return "Property [vegan] does not exist on this collection instance.", but something about your usage is treating it that way.无论哪种方式,
find()
都不会返回Collection
,因此$vegan->vegan
不会返回“Property [vegan] does not exist on this collection instance.”,但您的使用方式是这样处理的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.