Adding product to wishlist laravel
08:41 14 Oct 2019

I'm creating a functionality which allows the user to add product in wishlist, but I'm getting an error Trying to get property of non-object when I click the (whishlist blade), the error comes from this line

USD {{$wishlist->product->price }}

if I remove the $product it displays no price how do i fix this?

Wishlist Controller

public function index()
{
     $user = Auth::user();
     $wishlists = Wishlist::where("user_id", "=", $user->id)->orderby('id', 'desc')->paginate(10);
     return view('wishlist', compact('user', 'wishlists'));
}

Blade

@if (Auth::user()->wishlist->count() )
@foreach($wishlists as $wishlist)

USD {{$wishlist->product->price }}

USD {{$wishlist->product->name }}

@endforeach @endif

Wishlist.php

class Wishlist extends Model
{
protected $table = "wishlist";
protected $fillable=['product_id','user_id'];

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

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

User.php

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

Product.php

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