【问题标题】:How to return values in array of json using laravel query?如何使用 laravel 查询返回 json 数组中的值?
【发布时间】:2021-07-23 23:20:40
【问题描述】:
$search='m';
$data = Product::select("product_name")
        ->where('product_name','LIKE', '%' . $search . '%')
        ->get();
    
 return response()->json($data);

返回

[{"product_name":"MyProduct"},{"product_name":"MAC"}] .....

但我想要 [{"MyProduct"},{"MAC"}]

【问题讨论】:

  • return response()->json([$data]); 最好使用resources

标签: mysql laravel laravel-5 eloquent


【解决方案1】:

这是无效的JSON。 JSON对象,例如。 {} 需要密钥才能工作。

[{"MyProduct"},{"MAC"}]

我假设你想要一个字符串数组。

["MyProduct", "MAC"]

使用 pluck 以数组形式获取模型属性。这将返回字符串数组。

return response()->json($data->pluck('product_name'));

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-20
  • 2017-03-01
  • 2019-05-26
相关资源
最近更新 更多