0

I am on Laravel 7.x and I have two models (CustomerOrder composed of many CustomerOrderLines) with parent - child relationship. Parent (CustomerOrder) model has a json type field among its fields.

CustomerOrderResource.php:

return [
  'id' => $this->id,
  'wfx_oc_no' => $this->wfx_oc_no,
  'qty_json' => json_decode($this->qty_json)
];

CustomerOrderLineResource.php:

return [
  'id' => $this->id,
  'description' => $this->description,
  'customer-order' => $this->customerOrder
];

CustomerOrder->GET request returns properly formatted data as:

"data": {
    "id": 11,
    "wfx_oc_no": 12,
    "qty_json": {
        "L": "20",
        "M": "30",
        "S": "20",
        "XL": "100"
    }
}

But for CustomerOrderLine->GET, the response is as:

"data": {
    "id": 15,
    "description": "test desc",
    "customer-order": {
        "id": 11,
        "wfx_oc_no": 12,
        "qty_json": "{\"L\": \"20\", \"M\": \"30\", \"S\": \"20\", \"XL\": \"100\"}"
    }
}

json field is not properly formatted. It seems it doesn't go through Resource class. Please let me know, how can I get this fixed?

FYI

CustomerOrderLine.php:

public function parent()
{
   return $this->belongsTo(CustomerOrder::class);
}
Lakmal Premaratne
  • 1,159
  • 7
  • 18
  • 34

1 Answers1

0

Finally managed to get it solved using json cast. The field was included in $casts array in the model.

Lakmal Premaratne
  • 1,159
  • 7
  • 18
  • 34