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

davidifranco's avatar

Returning related data values

I have the following tables:

sku

  • id
  • sku name

orders

  • id
  • order number
  • ship date

orderDetail

  • id
  • order_id
  • sku_id

I am trying to return a JSON response of all 'orders' & 'orderDetails that have a given SKU. My sku model contains a hasMany relationship to orderDetails and hasManyThrough relationship to orders .

public function OrderDetails() { return $this->hasMany(OrderDetail::class); }

public function orders() { return $this->hasManyThrough(order::class, orderDetail::class, 'order_id', 'id'); }

My order model contains a hasMany relationship to orderDetail

public function orderDetails() { return $this->hasMany(orderDetail::class); }

what is the best way to query the orderDetail model to return data from the orderDetail model and the related orders model that will format well for JSON response.

return response()->JSON( compact( 'skuOrderData'), 200);

Disclaimer: if you already guessed, Im pretty new to this field and any help would be so appreciated. Thank you.

0 likes
2 replies
burlresearch's avatar

It looks like you're well on your way, I presume you can do something like:

$sku = Sku::whereName('someSKU')->firstOrFail();
$orders = $sku->orders();

As far as preparing the JSON response, you'll probably want to read up on API Resources. They are relatively new [L5.5] built-in transformers for your collection - and will help you do exactly what you want.

Please or to participate in this conversation.