Joven Dev
Joven Dev

Reputation: 309

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

Upvotes: 0

Views: 2598

Answers (2)

Ismail Shah
Ismail Shah

Reputation: 83

You can also hide the parameter that you don't want your customer or user to see go to the Model file and

protected $hidden=[
// here you will type the property name like
"update_at",
]

Upvotes: 0

FirstOne
FirstOne

Reputation: 6215

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;

Upvotes: 2

Related Questions