gpt4 book ai didi

php - 拉维尔 : How do I save a JSON object to MYSQL database?

转载 作者:太空宇宙 更新时间:2023-11-03 11:40:40 25 4
gpt4 key购买 nike

我想使用 Laravel API 将数据从前端发布到后端的 MYSQL 数据库。我尝试了以下代码,但它在尝试发布时输出了 500: Internal Server Error

public function postOrder(Request $request)
{
/*
$request is a JSON Object which looks like
{"order":{"table_id":2,"food_id":4,"status":1}}
*/

$order = new Order();
$order->table_id = $request->order->table_id;
$order->food_id = $request->food_id;
$order->user_id = $request->user_id;
$order->status = $request->status;
$order->save();

return response()->json(['message' => 'Order Added'], 201);
}

我应该json_decode($request)吗?怎么办?

当我error_log($request)时,这是我得到的:

Accept:          */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8
Connection: keep-alive
Content-Length: 60
Content-Type: application/json
Host: localhost:8000
Origin: http://localhost:8100
Referer: http://localhost:8100/
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML
, like Gecko) Chrome/55.0.2883.87 Safari/537.36
X-Xsrf-Token: eyJpdiI6IlJpNVV1ejhZTDVaSnVcL09lVkFIZER3PT0iLCJ2YWx1ZSI6IjNFK0
NnSXFsczd1eGJBRjZiZFc3U3lBUE9jR1lNZ0hSN0ZWNVpyWHlyWGE1TVZvZW9vK1F0eExXVjdkQzdPS
nBISEM3UXBINGQxZ09jTCttQ0huYmlnPT0iLCJtYWMiOiJmZWNiMTY1NTJjNjYyNDZjM2Q3YTE2N2Jl
NWNmYjgwYmNiMTlkNThjYWQ2NjEyYjk3YzQ4ZTVkYjQwMzFjY2VlIn0=

{"order":{"table_id":2,"food_id":4,"time":"333","status":1}}

最佳答案

你需要使用json_decode()来得到一个关联数组:

$json = '{"order":{"table_id":2,"food_id":4,"time":"333","status":1}}';

$array = json_decode($json, true);

var_dump($array['order']); //Here you can see that it is an associative array with the needed values now

然后您可以基于它创建一个模型。

$order = Order::create($array['order']);

关于php - 拉维尔 : How do I save a JSON object to MYSQL database?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42050555/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com