首页 > 解决方案 > 使用数据库中的值生成对象数组

问题描述

假设我有这张桌子:

id    |    product_item    |    head_count
1     |         400        |        2
2     |         401        |        5

所需的输出:

[
   {"product_item": 400,"head_count": 2},
   {"product_item": 401,"head_count": 5}
]

如何使用 Laravel 或 Eloquent 制作所需的输出?

标签: phplaravel

解决方案


Follow bellow step  
(1) declare in your controller **use DB**  

(2) write Query:  
$product = DB::table('tablename')->select('col1','col2')->get(); 

(3)dd($product); OR print_r($product);  

You got the result in $product  

echo json_encode($product); 

OR if you are load your view then,  
return view('VIEW_NAME',compact('product'));  

OR return like this and got the result on your view file.

return response()->json($product);

I hope its help.

推荐阅读