Reputation: 134
I am currently building my first App with Laravel and have stumbled upon the problem that I dont know how to setup the relationship Many-to-Many between the Models (User and Group).
I've created a board in which I store the relationship between all users and the Group they are in. My Problem is that I dont know how to acces and set this up in Laravel. Im not sure whether I have to user hasMany or belongsToMany.
I am trying to find a method to add a User to Group, so that a new entry will be created in the UserGroups table.
My tables:
User
Group
UserGroup
I appreciate any help, thanks!
Upvotes: 1
Views: 1697
Reputation: 163798
If you want to create a many-to-many relationship, it should be belongsToMany
, not hasMany
.
In the Group
model:
public function users()
{
return $this->belongsToMany(Group::class);
}
And in the User
model:
public function groups()
{
return $this->belongsToMany(User::class);
}
The pivot table should be called group_user
.
https://laravel.com/docs/5.4/eloquent-relationships#many-to-many
Upvotes: 0
Reputation: 1272
In the model class, use belongsToMany as demonstrated here: https://laravel.com/docs/5.4/eloquent-relationships#many-to-many
To add a user to a group, use attach(), as demonstrated here: https://laravel.com/docs/5.4/eloquent-relationships#the-create-method (scroll to many to many relations)
Upvotes: 0