thebigk's avatar
Level 13

Model Alias - 'Members' Vs. 'Users'

I've a users table that contains to all the registered users of the site. There's a User model to represent them.

Now I'm build a 'Groupsapplication which is a feature of my site. While creating models for the 'Groups' application on my site; I created aMembermodel. Now,Member` looks logical for Groups; but essentially, it's referring to users on the site.

Now I'm stuck at defining relationships. For example, I've this -

class Member extends Model {

public function groups() {
        return $this->belongsToMany(Group::class, 'groups_members', 'member_id', 'group_id')->withPivot('role');
    }

}

While this is okay, how do I access it in my controller? Let's say I wish to fetch all the groups that I'm a part of. How'd I go about fetching the groups?

Would appreciate your support.

0 likes
6 replies
andreich1980's avatar

$member->groups gives you all the groups the $member is in.

realrandyallen's avatar

The Member model seems unnecessary, why not just use the User model?

class User extends Model {
...
    public function groups()
    {
        return $this->belongsToMany(Group::class);
    }
...
}
class Group extends Model {
...
    public function members()
    {
        return $this->hasMany(User::class);
    }
...
}
thebigk's avatar
Level 13

@realrandyallen - Yes, it does look unnecessary; but I do not wish to overload my User model. There are several such apps on the site.

Is there a way to do this via Member model? I'm curious.

realrandyallen's avatar

@THEBIGK - Yup, you were on the right track in your original post...but you'd still need a relationship in your User model to relate your Member model to a User, so you might as well just bypass having a Member model altogether.

I understand not wanting to overload your User model but it's one more relationship in your User model - what's worse: that or having an additional model, an additional table, an additional migration, an additional seeder, an additional factory, additional tests and slightly more complex code.

Playing devils advocate here but I think it'd be better to just use User :)

1 like
thebigk's avatar
Level 13

I figured out a way to do this using whereHas; and I think I'll go with it. Thank you for your help, @real

1 like
skipper-henrik's avatar

Isn't it a thing about the is-a relation? I'm wondering how to manage the following. I have sailor and i have owner both of them are also user.

Please or to participate in this conversation.