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:
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:
IlluminateDatabaseEloquentCollection {#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');
}