i am currently working with laravel api and making cms using it. i need json response like this(1st output) but it is shwoing like next output: how can i solve this ?
{
"data": {
"id": 1,
"slug": "",
"title": "first",
"description": "This is the complete body for the CMS page",
"parentPageId": 0,
"image": "",
"metaDescription": "meta ",
"created_at": null,
"updated_at": null,
"creatorID": null,
"isActive": 0
"children": [
{
"title": "first",
"description": "This is the complete body for the CMS page",
"image": ""
}
]
},
}
but it is returning this outpur:
{
"data": {
"id": 1,
"slug": "",
"title": "first",
"description": "This is the complete body for the CMS page",
"parentPageId": 0,
"image": "",
"metaDescription": "meta ",
"created_at": null,
"updated_at": null,
"creatorID": null,
"isActive": 0
},
"children": [
{
"title": "first",
"description": "This is the complete body for the CMS page",
"image": ""
}
]
}
my code is
public function show($slug)
{
try {
$data = Page::where('slug', $slug)->orWhere('id', $slug)->firstOrFail();
$sub = Page::select('title', 'description', 'image')->where('parentPageId', $data->id)->get();
return['data'=>$data, 'children' => $sub];
} catch (Exception $e) {
return $this->returnJson(false, $e->getMessage(), $e->getCode());
}
}
how could i get the desired output ?
CodePudding user response:
Put the key of children
to the $data
, this maybe solves your issue.
public function show($slug)
{
try {
$data = Page::where('slug', $slug)->orWhere('id', $slug)->firstOrFail();
$sub = Page::select('title', 'description', 'image')->where('parentPageId', $data->id)->get();
$data['children'] = $sub;
return ['data'=>$data];
} catch (Exception $e) {
return $this->returnJson(false, $e->getMessage(), $e->getCode());
}
}
CodePudding user response:
You can also merge two query into single.
Page model
public function children()
{
return $this->hasMany(Page::class, 'parentPageId', 'id');
}
Controller
public function show($slug)
{
try {
return [ 'data' => Page::with(['children:title,description,image'])
->where(
fn($query) => $query->where('slug', $slug)
->orWhere('id', $slug)
)
->firstOrFail()
];
} catch (Exception $e) {
return $this->returnJson(false, $e->getMessage(), $e->getCode());
}
}