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

2

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

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

$grupo->usuarios[0]->aprovador
    
asked by anonymous 05.08.2015 / 01:04

2 answers

5

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

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

In this case to capture the field:

$grupo = App\Grupo::find(1);
foreach ($grupo->usuarios as $usuario) {
   echo $usuario->pivot->aprovador;
}
    
05.08.2015 / 01:19
0
$p = $usuario::find($id);
$grupo->p->aprovador;
    
05.08.2015 / 01:12