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

Vidarious's avatar

Eloquent: Many to Many Issues

I am having a rough time understanding how to implement this. I have 3 tables.

User

  • userID
  • username

Flag

  • flagID
  • description

UserFlag

  • userID
  • flagID

Users many have many different flags assigned to them. Alternately, flags can be assigned to multiple Users.

class User extends Model
{
    //Mass assignment.
    protected $fillable = ['username',
                           'displayName',
                           'passwordHash',
                           'givenName',
                           'familyName',
                           'email',
                           'statusID'];

    //Use a specific name for ID.
    protected $primaryKey = 'userID';

    //Use a specific table name.
    protected $table = 'User';

    //Relationship: Each user can have many flags. Many to many.
    public function flags()
    {
        return $this->belongsToMany('Flag', 'UserFlag', 'userID', 'flagID')
                    ->withPivot('description');
    }
}

And ...

class Flag extends Model
{
    protected $fillable = ['description'];

    protected $primaryKey = 'flagID';

    protected $table = 'Flag';

    //Relationship: Each status can be assigned to multiple users. Many to many.
    public function users()
    {
        return $this->belongsToMany('User', 'UserFlag', 'userID', 'flagID');
    }
}

When I ..

dd($usersFlag = User::find(1)->flags());
//OR
dd($usersFlag = User::find(1)->flags()->get());

I get nothing at all. I need to get all the flags a user has as well as a list of all the users that is assigned to a specific flag.

What am I doing wrong?

EDIT: I fixed it. I shouldn't have used withPivot('description'). I understood that wrong. Now I understand I can get the description of the flag with

$usersFlag = User::find(1)->flags->first()->description;

No delete thread option?

0 likes
0 replies

Please or to participate in this conversation.