2

I have this relationship in User.php Class:

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

And I have added $user_favourites = \App\User::find(auth()->user()->usr_id); to return info of a user.

Then, if I @dd($user_favourites->favourites), I get this as result:

enter image description here

Now I wanted to check if the current product id is equals to the prd_id of returned collection (which is shown as 14 in the image).

So how can I do that?

I tried adding this to the Model, but returned an error:

public function available_favourite($id) {
        return $this->favourites()->where('prd_id','=', $id);
    }

And call it like this:

@dd($user_favourites->available_favourite($product->prd_id)->get())

And here is the error:

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'prd_id' in where clause is ambiguous

So how can I check that current product id exist in $user_favourites->favourites ?

yetep93258
  • 33
  • 1
  • 13

1 Answers1

0

you can use the collection's contains method to check if such prd_id exists.

public function available_favourite($id) : bool 
{
   return $this->favourites->contains('prd_id', $id);
}

//then check
dd($user_favourites->available_favourite($product->prd_id))

exclude () in $this->favourites() just to reference the relationship.

More info.

jade
  • 781
  • 12
  • 24
  • Would u check this plz: https://stackoverflow.com/questions/70997829/how-can-i-do-this-with-eloquent-relationship – yetep93258 Feb 05 '22 at 12:14