Reputation: 1066
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?
Upvotes: 0
Views: 708
Reputation: 111829
Although error is obvious (mentioned in comment) you could rewrite the whole thing:
$categories = Category::withCount('products')->get(); // you load count to not make n+1 queries
$categoriesWithProducts = $categories->filter(function($category) {
return $category->products_count > 0
})->values();
return response()->json(categoriesWithProducts);
Of course you could make it even simpler:
return response()->json(Category::withCount('products')->get()
->filter(function($category) {
return $category->products_count > 0
})->values()
);
But in fact the best way would be using Eloquent relationships so you could use:
return response()->json(Category::has('products')->get());
Upvotes: 2