Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

noddy's avatar

How to adjust JSON output before sending response

Hi there,

Im not sure how to structure my code, so asking for some assistance.

In my Clients controller function below, I am retrieving data from 3 tables: clients, addresses and orders. Id like to pass this in JSON format in a way that can be consumed directly - ie. the view will only render it.

    $query = Client::with('orderSummary', 'addressSummary')
      ->select(['id', 'salutation', 'first_name', 'last_name', 'gender'])
      ->paginate(10);
    return response()->json($query);

The sample of the JSON response from the function above is shown below (im receiving 10 contact records in total):

   {
     "id": 1,
     "salutation": "Prof.",
     "first_name": "Jenny",
     "last_name": "Dubbet",
     "gender": F,
     "order_summary": [
       {
         "total": "6945.00",
         "count": 12
       }
     ],
     "address_summary": {
       "phone_mobile": "123456789",
       "email": "carel.marco@yahoo.com",
       "city": "Oakville",
       "country": "Mongolia"
     }
   }

However, I would like to restructure the above JSON array BEFORE sending the response, such that the client receives something like this for each record:

{
  "Client": "Prof Jenny Dubbet<br>Oakville, Mongolia",
  "Orders": "12 Orders<br>Total Sales: $6945.00",
  "Contact": "Email: carel.marco@yahoo.com<br>Phone: 123456789"
}
  • Where would be the best place to add a function to re-structure the above data (controller? model? helper?) and how do I pass my query result to such a function?
  • How can this be improved? Totally open to suggestions.

FYI - Im not using blade as this is primarily for a single page JS app. The data is being requested by the client and then displayed without room for any further manipulation on the client.

Do Let me know if anything seems unclear.

0 likes
1 reply
noddy's avatar

Updating my own post - Ive decided to update my sql queries (e.g. use concat to join names) and then fractal to transform the data for the view.

The fractal methods are being called from the same controller function listed above.

Please or to participate in this conversation.