Laravel: Nested relationship method

  eloquent, laravel

I have the following models:

users

  • id
  • name

organisation_members

  • id
  • organisation_id (FK to organisations)
  • user_id (FK to users)
  • unqiue(organisation_id, user_id)

organisations

  • id
  • name

A user can be a member to many organisations.

My models are written as follows

class User extends Model {
    public function organisationMembers(): HasMany
    {
        return $this->hasMany(OrganisationMember::class);
    }
  
    public function organisations()
    {
        // TODO: how do I do this one
    }
}
class OrganisationMember extends Model {
    public function organisation(): BelongsTo
    {
        return $this->belongsTo(Organisation::class);
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }
}
class Organisation extends Model {
    public function organisationMembers(): HasMany
    {
        return $this->hasMany(organisationMember::class);
    }
}

How can I write a relationship method in the User model for organisations?

Source: Laravel

Leave a Reply