1

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');
    }
yetep93258
  • 33
  • 1
  • 13
  • A _new_ user certainly doesn't have any favourites yet. Use the [Query Builder](https://laravel.com/docs/8.x/queries) to get all favorites for all users – brombeer Feb 05 '22 at 10:53
  • @brombeer But query builder does not look like to clean codes. Is there any Eloquent way for doing this except making a separated Model ? – yetep93258 Feb 05 '22 at 10:57

1 Answers1

2

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();
N69S
  • 16,110
  • 3
  • 22
  • 36
  • if two different users add same product, it returns only one of them. https://stackoverflow.com/questions/70997829/how-can-i-do-this-with-eloquent-relationship – yetep93258 Feb 05 '22 at 12:08
  • @yetep93258 yeah but the attribute favoritees_count will have 2 as value – N69S Feb 05 '22 at 19:29