【问题标题】:Property [id] does not exist on this collection instance - Laravel 6此集合实例上不存在属性 [id] - Laravel 6
【发布时间】:2021-02-04 13:52:10
【问题描述】:

我正在尝试使用 foreach 将数据加载到表中,但出现错误

此集合实例上不存在属性 [id]。

我做错了什么?

响应如下所示:

{
   "id": 1,
   "name": "Apple",
   "messages": [
      {
         "id": 7,
         "received": 0
      }
   ]
}   

控制器

public function show()
{
    $items = Item::with('messages')->where('user_id', Auth::user()->id)->get();
    return view('home', compact('items'));
}

查看

@foreach($details as $detail)
    <td>{{ $details->messages->id }}</td>
@endforeach

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    看起来您在Item 表上与Messages 表执行的连接会返回messages 字段中的列表。此处显示:

    {"id":1,"name":"Apple""messages":[{"id":7,"received":0}]}  
    

    注意[{"id":7,"received":0}]

    要获取消息的单个 ID,您首先需要索引到 messages 列表。或者您可以将查询更改为仅从每个项目中选择一条消息。

    【讨论】:

      【解决方案2】:

      试试这个 $userId = Auth::id();然后 where('user_id', $userId)->get()

      【讨论】:

      • 欢迎来到 SO 。请注意,非常简短的答案可能对原始海报没有帮助。请更详细地解释它并包含一个正确格式化的代码示例。
      猜你喜欢
      • 1970-01-01
      • 2023-03-12
      • 2018-04-12
      • 1970-01-01
      • 2021-11-14
      • 1970-01-01
      • 1970-01-01
      • 2020-07-11
      相关资源
      最近更新 更多