rohan sa rohan sa - 2 years ago 127
PHP Question

Laravel Many to Many Relationship ( hasMany or belongsToMany )

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:


  • ID

  • Name

  • Email


  • ID

  • Name

  • Creator_ID


  • User_ID

  • Group_ID

I appreciate any help, thanks!

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download