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

tealiedie's avatar

laravel relation

Hi guys, i need help using relations. i have these tables. (correct me if i'm doing the relation / table wrong)

// 1. Users table
id,username,password
// 2. groups table
/* user_id is the moderator / owner of the group */
id,user_id,group_title

// 3. group_user (pivot table)
/* user_id here is the id of the user that joined the group */
id, group_id, user_id, property_id,sharables

for example. user1 and user2 have group1 and group2. now how can i get the member of group1 that is owned by user1 ? ie: user3 and user4 joined the group1 i tried belongsToMany()->withPivot(); but when i logged-in the user3 and get the relation joinedgroup it always returning null.

0 likes
3 replies
Hesto's avatar

Your logic seems to be correct. Show me your code so i can look for mistakes.

tealiedie's avatar

@Hesto here.

// User.php model
public function ownedgroups()
{
      return $this->hasMany('App\Group');
      // ->withPivot('sharables', 'property_id');
}
public function joinedgroups()
{
      return $this->belongsTomany('App\Group', 'group_user', 'group_id', 'user_id')
            ->withPivot('sharables','property_id');
 }

//Group.php model
public function moderator()
{
     return $this->belongsTo('App\User');
}

for example i logged user3, and get the groups that user3 joined. it always returning an empty collection.

Hesto's avatar

@tealiedie Change that method:

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

to

public function moderator()
{
     return $this->belongsTo('App\User','user_id');
}

Becouse when you use "belongsTo" with "moderator" method name Eloquent will look for "modarator_id" in your sql User table. But you named it user_id so relationship cannot be found. So you have to show Eloquent which field is responsible for relationship.

Please or to participate in this conversation.