0

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?

5
  • use $i <= $count Commented Sep 19, 2018 at 12:13
  • try if(count($categories[$i]->products) > 0) { Commented Sep 19, 2018 at 12:14
  • 1
    Move your return so it's after (outside) the loop. Currently, it will always return the data after the first iteration. Commented Sep 19, 2018 at 12:30
  • @MagnusEriksson i actually missed that. Thanks it solved it. Commented Sep 19, 2018 at 12:36
  • Voting to close as a typo. Commented Sep 19, 2018 at 13:26

1 Answer 1

2

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());
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot, quite enlightening.
instead of using array I'd recommend a collection. $categoriesWithProducts = collect(); Then in you're loop do $categoriesWithProducts->push($categories[$i]); and then return $categoriesWithProducts;

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.