该集合实例上不存在属性[vegan]。拉拉韦尔

时间:2019-10-04 13:31:03

标签: php laravel eloquent laravel-5.8

我试图根据表中的特定列是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)

这会产生未定义的偏移错误

2 个答案:

答案 0 :(得分:1)

问题是查询后您缺少first()

$vegan = Company::find($id)->first();
$vegetarian = Company::find($id)->first();

答案 1 :(得分:1)

在这一行中,您要通过URL参数将Company注入show方法中:

public function show(Company $id){ ... }

此时,$idCompany实例或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不会返回“此集合实例上不存在属性[纯素]。”,但是有关您的用法正在以这种方式对待。