I have two models:
Category
Model has: id PRIMARY_KEY
, category_name
, ...
Item
Model has: id PRIMARY_KEY
, item_name
, category_id
(is id on category table), ...
I wish to achieve this JSON response:
Item:
{
"id": 1,
"item_name": "some item name",
"category": {
"id": "5",
"category_name": "some category name"
}
}
So far I have managed to achieve only response:
{
"id": 1,
"item_name": "some item name",
"category_id": "5", // i dont want it to appear here!
"category": {
"id": "5",
"category_name": "some category name"
}
}
With query:
$data = Item::select('id', 'item_name', 'category_id')->with(['category' => function ($query) {
$query->select('id', 'category_name');
}])->get();
return response()->json($data);
I tried select('id', 'item_name')
instead of select('id', 'item_name', 'category_id')
, but it fails, since it required 'category_id' for with
to work. Any clean solutions to this?