Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

infotechmt's avatar

Relationship and save to pivot table

Hi, I just begin to learn Laravel in few days. In my situation, I have three tables:

users( id, name)

groups( id, name)

group_has_users( group_id, user_id)

group has many users, but user just belong one group, how about the below Relationship, then after I save a group, how to take the ID of group and save to "group_has_users" table

in Group model I have:

public function users()
{
    return $this->morphMany('App\User', 'group_has_users');
}

in User model I have:

public function group()
{
    return $this->hasOne('App\Group');
}

thank you

0 likes
2 replies
biishmar's avatar

in Group model I have:

public function users()
{
    return $this->belongsToMany('App\User', 'group_has_users');
}

in User model I have:

public function group()
{
    return $this->hasOne('App\Group');
}

Create

$user = User::find(auth()->id());

$res = $user->group()->attach($groupId) // single row will be created
$groupIds = [1,2,3];
$res = $user->group()->attach($groupIds) // multiple row will be created

at above coding user id will be automatically insert due to relationship
1 like
benr1804's avatar
benr1804
Best Answer
Level 9

If you have the access to modify the database a better design would be to have a group_id column on your users table and delete the group_has_users pivot table.

It's just a one to many relationship:

User model:

public function group()
{
    return $this->belongsTo('App\Group');
}

Group model:

public function user()
{
    return $this->hasMany('App\User');
}
1 like

Please or to participate in this conversation.