Search code examples
phpjsonlaravel-5.3response

Laravel php How to return response with certain parameters in JSON format


When i received the message in json format as below:

{
  "Details":{
      "Type":"Cash",
      "Payid":"PAY123456",
      "Amount":"9000,00",
      "Status":"Successful",
  }
}

I need to return response in the following JSON format with two parameters only (Type & Payid) that received

{
  "Details": {
    "Type": "Cash",
    "Payid": "PAY123456"
    }
}

Currently in my controller it will return the whole details that received. But how do I modified it, so that it will just return the certain parameters.

public function returnResponse(Request $request)
{
    $datas= $request->getContent();
    $returnData= json_decode($datas, true);
    return response()->json($returnData);
}

Solution

  • This is one way to do it:

    public function returnResponse(Request $request){
        $datas = $request->getContent();
        $parsedJson = json_decode($datas, true);
        $returnData = array('Details' => array(
            'Type' => $parsedJson['Details']['Payid'],
            'Payid' => $parsedJson['Details']['Payid'],
            'Confirmation' => 0 // do the same in this line if you want to add more
        ));
        return response()->json($returnData);
    }
    

    This code assumes you'll always have 'Type' and 'Payid' inside 'Details'.

    The result will be:

    Array
    (
        [Details] => Array
            (
                [Type] => PAY123456
                [Payid] => PAY123456
                [Confirmation] => 0
            )
    
    )
    

    Note, if you just want to add Confirmation to the original array, you can use:

    $returnData['Details']['Confirmation'] = 0;