0
votes

I want the details of product that are added to wishlist table. I'm getting the data from wishlist table but i want to establish relation from product and user model also so that i can get the details of the product. My table Structure is :

Wishlists table:

id | product_id | user_id 

products table :

id | name | price 

users table :

id  | first_name  | last_name | contact 

Wishlist Model :

public function user(){
   return $this->belongsTo(User::class);
}

public function product(){
   return $this->belongsTo(Product::class);
}

Product Model :

public function wishlist(){
    return $this->hasMany(Wishlist::class);
 }

 public function users()
{
    return $this->belongsToMany(User::class);
}

Users Model :

public function wishlist(){
    return $this->hasMany(Wishlist::class);
 }

I'm getting data from wishlist table through this code but can't get data from product table :

return Wishlist::with('product')->where('user_id', auth()->id())->get();  

product relation is returning null

1

1 Answers

1
votes

I think it's better to use a Many To Many relationship. In this case, you don't need the Wishlist model.

Product.php

public function users()
{
    return $this->belongsToMany(User::class,'wishlists');
}

User.php

public function products()
{
    return $this->belongsToMany(Product::class, 'wishlists');
}

Then you can get the user's wishlist like this:

auth()->user()->products;