php – How to get count for all products for all categories (i.e all records on many-to-many table) with laravel 5.2-ThrowExceptions

Exception or error:

This what i want to do is to take the count of records from many-to-many table. I can do it with a simple query, but I want to use the ORM of Laravel 5.2. These are my models:

Category model

class Category extends BaseModel {
    protected $table = 'categories';

    public function products() {
        return $this->belongsToMany('App\Models\Product', 'product_category');
    }

Product model

class Product extends BaseModel {
    protected $table = 'products';

    public function categories() {
        return $this->belongsToMany('App\Models\Category', 'product_category')->withTimestamps();
    }

I want to add a method in the Category model or using the Laravel ORM to take the number of all products for all categories i.e the number of all records from the product_category table. How can I do it ?

How to solve:

If I am understanding you right, you want a method that will return the number of all records in the product_category table. If that is the case, here you go:

public function numberOfProductCategories() {
    return DB::table('product_category')->count();
}

You may find more info about this here: https://laravel.com/docs/5.2/queries

Leave a Reply

Your email address will not be published. Required fields are marked *