Reputation: 85
the problem is that I have forms and I want to get all the members of it.
I have created a table pivot groupes which retrieves form_id from the table forms and user_id from the table users. but when I try to retrieve the information I get this : Attempt to read property "firstname" on bool (View: /.../resources/views/groupes/list.blade.php)
In my Models I have : Forms :
public function user()
{
return $this->belongsTo(User::class);
}
public function groupe()
{
return $this->belongsToMany(Groupe::class);
}
User:
public function forms()
{
return $this->hasMany(Forms::class);
}
public function groupe()
{
return $this->belongsToMany(Groupe::class);
}
list.blade.php ($forms correspond to 1 single form I had made a foreach before of all my forms):
@foreach($forms->user as $user)
{{$user->firstname}}
@endforeach
Upvotes: 0
Views: 100
Reputation: 329
Groupe
is your pivot table, which contain user_id and form_id. As the docs described, if the pivot table is not joining the two related model names in alphabetical order (should be form_user
in this case), then you need to include the table name, which is groupe
:
public function groupe(): BelongsToMany
{
return $this->belongsToMany(Groupe::class, 'groupe');
}
And if you want to get User
of a form
, then:
public function getFormWithUser()
{
$form = Form::with('groupe')->first();
}
*note: But I'm a little confused with form
relation in User
model and vice versa, if this relation is Many to Many
(since there's groupe
pivot model), how could they related to each other directly ?
Upvotes: 1