Support the ongoing development of Laravel.io →
posted 8 years ago
Eloquent
Last updated 1 year ago.
0

I have a similar situation where I have users, I have accounts and I have roles. You can simply swap out Account with Organization.

The roles migration ...

class CreateRolesTable extends Migration
{
 
    public function up()
    {
        Schema::create('roles', function (Blueprint $table)
        {
            $table->increments('id');
            $table->string('name');
        });
    }
 
    public function down()
    {
        Schema::drop('roles');
    }
 
}

The migration that creates the pivot table ...

class CreateRoleUserAccountTable extends Migration
{
 
    public function up()
    {
        Schema::create('role_user_account', function (Blueprint $table)
        {
            $table->integer('role_id')->unsigned();
            $table->integer('user_id')->unsigned();
            $table->integer('account_id')->unsigned();
            $table->timestamps();
            $table->unique(['account_id', 'user_id']); // This ensures that a user can have only ONE role per account
            $table->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade')->onUpdate('cascade');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade')->onUpdate('cascade');
        });
    }
 
    public function down()
    {
        Schema::drop('role_user_account');
    }
 
}

User model ...

    // Determine which role a user has for a specific account
    public function AccountRole($account_id)
    {
        return $this->belongsToMany('Role', 'role_user_account', 'user_id', 'role_id')->wherePivot('account_id', $account_id)->withTimestamps()->first();
    }
 
    // Fetch all of the accounts/roles for this user
    public function AccountRoles()
    {
        return $this->belongsToMany('Role', 'role_user_account', 'user_id', 'role_id')->withPivot('account_id')->withTimestamps();
    }
 
    // Fetch all the accounts for which this user is an Admin (note that the admin role is the first record in the roles table id=1)
    public function AdminAccounts()
    {
        return $this->belongsToMany('Account', 'role_user_account')->wherePivot('user_id', $this->id)->wherePivot('role_id', 1)->withTimestamps();
    }

Account model ...

    public function AccountUsers()
    {
        return $this->belongsToMany('User', 'role_user_account', 'account_id', 'user_id')->withTimestamps();
    }
Last updated 8 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.