Danu Akbar Danu Akbar - 6 months ago 50
JSON Question

Laravel 5 Can't Recieve / Read Json Format (POST METHOD)?

I've successfully created REST using laravel for GET method. My laravel can't read JSON data, but if i use form-data, the laravel can recieve / redad JSON normaly. Here's my controller:

public function store(){
$tagihan=new tagihan;
$tagihan->no_rek_pelanggan=Request::input('no_rek_pelanggan');
$tagihan->keadaan_meteran=Request::input('keadaan_meteran');
$tagihan->angka_meteran=Request::input('angka_meteran');
$success=$tagihan->save();

if(!$success)
{
return Response::json("error saving",500);
}
return Response::json("success",201);
}`


I also add
use Request;
on my controller.

Here's my result when i use form-data

Success when i use form-data

Here's my result when i use raw (JSON)

Here's my result when i use raw (JSON)

my laravel can't read / recieve JSON data.

JSON i've tried to submit:

[{
"id":20,
"no_rek_pelanggan":11117,
"keadaan_meteran":0,
"angka_meteran":600,
"status":0
}]


["tagihan": {
"id":20,
"no_rek_pelanggan":11117,
"keadaan_meteran":0,
"angka_meteran":600,
"status":0
}]'


"tagihan" is my mysql table name.

Answer

Have you tried something like this? That your request data is always in JSON proper format?

public function store(Request $requestData){
    $request = json_encode($requestData);
    //check here if all data is now good
    dd($request);

    $tagihan=new tagihan;
    $tagihan->no_rek_pelanggan=$request->no_rek_pelanggan;
    $tagihan->keadaan_meteran=$request->keadaan_meteran;
    $tagihan->angka_meteran=$request->angka_meteran;
    $success=$tagihan->save();

    if(!$success)
    {
        return Response::json("error saving",500);
    }    
    return Response::json("success",201);
}
Comments