微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

获取数组 Laravel ->first();错误 json_decode() 需要参数

如何解决获取数组 Laravel ->first();错误 json_decode() 需要参数

您好,出于某种奇怪的原因,我通过 Laravel 中的数据库查询获得了一个数组,但无法获取该数组

在 ->first();获取错误json_decode() expects parameter 1 to be string,object given 在 ->get();作品

如果可以使用 GET 但我只需要第一个

示例: $iduserverified = DB::table('items')->where('id',$request->id)->first(); $decadened = json_decode($iduserverified,true);

$decadened Ahrows:

{#1967 ▼
  +"id": 8
  +"restaurant_id": 1
  +"item_category_id": 1
  +"name": "Falso Teleport"
  +"price": "321.00"
  +"old_price": "0.00"
  +"image": "https://i.ytimg.com/an_webp/ifkGKPtSfeo/mqdefault_6s.webp?du=3000&sqp=cpsFhoYG&rs=AOn4CLCIHKSJbZ265w_iWuFUNsnkWJwzfw"
  +"is_recommended": 0
  +"is_popular": 0
  +"is_new": 1
  +"created_at": "2021-06-17 18:07:22"
  +"updated_at": "2021-06-17 19:00:43"
  +"desc": "<p>3</p>"
  +"placeholder_image": null
  +"is_active": 1
  +"is_veg": null
  +"order_column": null
  +"user_id": "3"
}

用 ->get();我没有从 json 解码中得到任何错误,它可以工作,但我只需要获取一个表 ->first();

用 ->get();演员和它的工作

Illuminate\Support\Collection {#1761 ▼
  #items: array:1 [▼
    0 => {#1967 ▼
      +"id": 8
      +"restaurant_id": 1
      +"item_category_id": 1
      +"name": "Falso Teleport"
      +"price": "321.00"
      +"old_price": "0.00"
      +"image": "https://i.ytimg.com/an_webp/ifkGKPtSfeo/mqdefault_6s.webp?du=3000&sqp=cpsFhoYG&rs=AOn4CLCIHKSJbZ265w_iWuFUNsnkWJwzfw"
      +"is_recommended": 0
      +"is_popular": 0
      +"is_new": 1
      +"created_at": "2021-06-17 18:07:22"
      +"updated_at": "2021-06-17 19:00:43"
      +"desc": "<p>3</p>"
      +"placeholder_image": null
      +"is_active": 1
      +"is_veg": null
      +"order_column": null
      +"user_id": "3"
    }
  ]
}

解决方法

在 Laravel 中

->get()

根据您的查询返回数据集合。 (集合就像数组,它们包含多个模型实例)

另一方面:

->first()

只返回结果查询的第一行,这意味着结果不是一个数组,而是一个模型实例,所以你不需要json_decode它,它已经是一个模型,你可以像这样简单地使用它.

$iduserverified = DB::table('items')->where('id',$request->id)->first();
$itemName = $iduserverified->name; // assuming the item model has name.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。