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?
The solution was to make it hidden
in Collection
:
$data = Item::select('id', 'item_name', 'category_id')->with(['category' => function ($query) {
$query->select('id', 'category_name');
}])->get()->makeHidden('category_id');
return response()->json($data);
Yes you cannot remove category_id
as it's needed to create the relationship. You can instead do something like this after you query and set $data
.
$response = [];
$data->each(function ($value) use (&$response) { // pass $response by reference
unset($value->category_id);
$response[] = $value;
});
return response()->json($response);