Peter Amo
Peter Amo

Reputation: 201

How to get all results of a table with Many To Many relationship

I'm working on an Online Store project and I wanted to create Add To Favourite system for users to add products that they like to their favourite list.

So I have created a table named favourite_products which goes like this:

enter image description here

So the usr_id stands for user id and prd_id stands for product id.

Now I wanted to get all the data from this table.

So I tried adding this to the Controller:

$userFavourites = new User();
dd($userFavourites->favourites);

But it does not return data and shows this empty collection:

Illuminate\Database\Eloquent\Collection {#2862 ▼
  #items: []
}

However data already exists there.

So my question is, how can I show all the results from favourite_products at a table with User Many To Many relationship?

Here is the User.php Model:

public function favourites()
    {
        return $this->belongsToMany(Product::class, 'favourite_products', 'usr_id', 'prd_id')->withTimestamps();
    }

And this the Product.php Model:

public function favouritees()
    {
        return $this->belongsToMany(User::class, 'favourite_products', 'prd_id', 'usr_id');
    }

Upvotes: 1

Views: 1101

Answers (1)

N69S
N69S

Reputation: 17205

if your goal is to get all the favorite product of all users, do

Product::whereHas('favouritees')->get();

you can also get a count with it

Product::whereHas('favouritees')->withCount('favouritees')->get();

Upvotes: 2

Related Questions