2017-02-05 117 views
0

我想使用Laravel API將數據從Frontend發佈到後端的MYSQL數據庫。我嘗試了以下代碼,但在嘗試發佈時輸出500: Internal Server ErrorLaravel:如何將JSON對象保存到MYSQL數據庫?

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}} 
+0

的可能的複製[Laravel:如何JSON格式數據存儲在數據庫(http://stackoverflow.com/questions/37803214/laravel-how-to-store-json-format-data-in - 數據庫) – manniL

+0

這個問題沒有適當的解決方案來解決這個問題。 – anonym

+0

哦,是的。你是對的,我很抱歉!給我一秒 – manniL

回答

1

,可能是解決辦法:

json_decode($request, true)['order']['table_id'] 
2

您需要使用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 

然後你可以cr吃掉一個基於它的模型。

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

@anonym有幫助嗎? – manniL

相關問題