Попробуйте это ::
public function getSubCategory(Request $request)
{
$response = array();
try {
$allData = array();
// get all parent category
$categories = Category::where(['status' => 0, 'parent_id' => 0])->get();
foreach ($categories as $key=>$sub) {
// now take one by one it's child category
$subCategory = Category::where('status', 0)->where('parent_id', '=', $sub->id)->get();
$subCat = array();
// set parent category title
$allData[$key]['parent'] = $sub->title;
foreach ($subCategory as $k=>$subcat) {
$subCat[$subcat->id] = $subcat->title
}
// set child category array
$allData[$key]['child'] = $subCat;
}
if (count($allData) > 0) {
$response = (new ApiMessageController())->successResponse($allData, "Categories List Found!");
} else {
$response = (new ApiMessageController())->failedresponse("No Categories List Found");
}
} catch (\Illuminate\Database\QueryException $ex) {
$response = (new ApiMessageController())->queryexception($ex);
}
return $response;
}
Выход:
array(
0 => array(
'parent' => 'parent 1',
'child' => array(
'1' => 'child 1',
'2' => 'child 2'
)
),
1 => array(
'parent' => 'parent 2',
'child' => array(
'1' => 'child 1',
'2' => 'child 2'
)
)
)
Может быть, это вам поможет.