I am trying to get all categories that have products from the database and push them into another array.
I have four 3 categories and two of them have products.
Here is my code:
$categories = Category::all();
$count = count($categories);
$categoriesWithProducts = array();
for($i = 0; $i < $count; $i++) {
if($categories[$i]->products->count() > 0) {
array_push($categoriesWithProducts, $categories[$i]);
}
return response()->json($categoriesWithProducts);
}
I get an array with just one item instead of two.
Where am i going wrong?
if(count($categories[$i]->products) > 0) {returnso it's after (outside) the loop. Currently, it will always return the data after the first iteration.