Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

368
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda