Recovering value in the pivot table as property of a relationship part

Asked

Viewed 522 times

2

I have the relationship manyToMany amid Grupos and Usuarios and a pivot table grupo_usuario which stores the keys and an extra field aprovador, boolean, which serves to indicate whether the user in the relationship can vote or not.

I don’t know how to insert the attribute aprovador for the user only in this relationship to be able to do something like:

$grupo->usuarios[0]->aprovador

2 answers

5


According to the documentation of the Laravel, you need to add withPivot in their relationship:

return $this->belongsToMany('App\User', 'grupo_usuario', 'grupo_id', 'user_id')->withPivot('aprovador');

In that case to capture the field:

$grupo = App\Grupo::find(1);
foreach ($grupo->usuarios as $usuario) {
   echo $usuario->pivot->aprovador;
}
  • You’re right Lucius. Thank you for your help.

0

$p = $usuario::find($id);
$grupo->p->aprovador;
  • Here it didn’t work

Browser other questions tagged

You are not signed in. Login or sign up in order to post.