phplaravelmany-to-manylaravel-5.8laravel-relations

How can I check a variable exist in returned collection relationship or not


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 ?


Solution

  • 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.