Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

369
Vistas
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 ?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

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.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda