dynamic
dynamic

Reputation: 207

Laravel 5.4- How to receive JSON data from server and save in Database

I am using webservices. My requirement is to receive JSON data from server and store in DB[order table].Customers use to place mutliple Order in mobile.The same has to be received in laravel controller and stored in the order table.I should not use form only via controller I should receive data. I am new to this concept of webservices and JSON.

public function receive(Request $request)
{       
    $data = $request->json()->all();
    $order = new order();
    $order->product_int = $request->input('products');
    $order->quantity_float = $request->input('quantity');
    $order->amount_float = $request->input('amount');       
    $order->save();        
}

In api.php , I am calling Route::get('/receive', 'OrderController@receive'); The above piece of code does not work.suggestions on how to receive JSON data as function parameter and how to save to DB.

Upvotes: 1

Views: 4988

Answers (1)

manian
manian

Reputation: 1438

You should receive an associative array by using Input::all method in Laravel like below,

public function receive(Request $request)
{       
   $data = Input::all(); //$data = $request->json()->all(); should also work
   $order = new order();
   $order->product_int = $data['products'];
   $order->quantity_float = $data['quantity'];
   $order->amount_float = $data['amount'];       
   $order->save();        
}

And probably, you might want to change your route to have post instead of get,

Route::post('/receive', 'OrderController@receive'); 

If you dont want a form to submit, then you can use CURL to post data to your API,

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"YOUR-API-URL-HERE");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('products' => $value, 'quantity' => $quantity, 'amount' => $amount)));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
curl_close ($ch);

Upvotes: 3

Related Questions