user8001788
user8001788

Reputation:

Counting Rows based on Identifier - Laravel

I have a many to many relationship between two tables. categories and products tables and the pivot table is category_product.

In my category table, i have an attribute no_of_products which is to keep the number of products under that category and it is nullable (because, i create the category before adding the products under the category).

How do i update the no_of_products after saving a product under a category. This is what i have tried but i am getting confused.

Do i have to count from the pivot table where i have the relations inserted?

I am beginner with database and laravel.

ProductsController

 public function store(Request $request)
    {
        $product = new Product(array(
               'name'  => $request->get('name'),
            ));

                 $product->save();
                 $product->saveProduct($request->get('category'));  

                 $count_product = Product::count();               

             }

Upvotes: 0

Views: 35

Answers (1)

Raza Mehdi
Raza Mehdi

Reputation: 941

You don't need to store total products count in database. You can simply update $withCount property in your App\Category model like this:

protected $withCount = ['products'];

This will automatically give you total number of products for a category through a property $category->products_count

Upvotes: 1

Related Questions