简体   繁体   中英

Laravel: How do I save a JSON object to MYSQL database?

I want to post data from Frontend to MYSQL database in the backend using Laravel API. I tried the following code, but it outputs a 500: Internal Server Error while trying to post.

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);
}

Should I json_decode($request) ? How?

When I error_log($request) , here's what I get:

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

You need to use json_decode() to get an associative array:

$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

Then you can create a model based on it.

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

那可能是解决方案:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM