Search code examples
phplaravelmodelmany-to-manyrelationship

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:

User

  • ID
  • Name
  • Email

Group

  • ID
  • Name
  • Creator_ID

UserGroup

  • User_ID
  • Group_ID

I appreciate any help, thanks!


Solution

  • 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