【问题标题】:Property [vegan] does not exist on this collection instance. Laravel此集合实例上不存在属性 [vegan]。拉拉维尔
【发布时间】: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)-&gt;firstOrFail();

标签: php laravel eloquent laravel-5.8


【解决方案1】:

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

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

【讨论】:

  • 现在我得到 Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_RECOVERABLE_ERROR) Too little arguments to function Illuminate\Support\Collection::get(), 0 pass in C:\xampp\htdocs\EdenBeauty \app\Http\Controllers\ProductsController.php 第 55 行,预计至少 1 个
  • 先尝试,更新我的答案。顺便说一句,请尝试在您的 return 语句之前执行dd($id, $vegan, $vegetarian),并查看是否传递了任何数据。
  • find()的功能和where('id', $id)-&gt;first()一样
  • @N69s 我不知道,不。抱歉,里面应该放什么?
【解决方案2】:

在这一行中,您通过 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-&gt;vegan 不会返回“此集合实例上不存在属性 [vegan]。”,但您的使用方式是这样处理的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2022-07-08
    • 2023-01-23
    • 2020-11-12
    • 2019-03-23
    • 2020-07-11
    • 2017-05-12
    相关资源
    最近更新 更多