I have 2 tables one is category that has subcategories and I want to fetch the records and put in a single array. I have implemented this code:
public function searchItem(){
$categories = ServiceCategory::with('subCategories')->get();
$categoryArray = [];
foreach ($categories as $category) {
$categoryArray[] = [
$category->category,
$category->subCategories->pluck('subcategory')->toArray(),
];
}
return $categoryArray;
}
The results I get is:
[["plumbing",["fitting","joints","pipe setting","wall setters","roof setters","drainage","walls and interior"]]
but what I want is something like this:
["plumbing","fitting","joints","pipe setting","wall setters","roof setters","drainage","walls and interior"]
Your sample output seems to indicate that you are only getting one row of results from
$categories, so I am not sure that you actually need thatforeach()loop.The only time I ever use
array_push()is when it is necessary to push multiple items into an array. I find it very appropriate for this case to produce a flat result array.Using this technique, the returned array will be a flat array thanks to the spread operator (
...) before the pluckedsubCategoriesarray.