Support the ongoing development of Laravel.io →
Database Eloquent Architecture
Last updated 2 years ago.
0

Hey Ross,

Can you give an example of the business case that would require such a complex set up for your ACLs? From the sounds of it, a user has as many roles as groups they belong to but the role is determined by the Group the user is acting on behalf of? Honestly, that sounds like a nightmare to me.

Maybe you're over thinking it?

0

In each group there are different roles: leader, participants, newcomers and so on. A user can join multiple groups. In each group he joins he can have a different role - in one group he can be the leader, in another - participant and so on.

In pure sql I'll just create table users_groups_roles with foreign keys to the main tables, but I can't figure out how to do it with Eloquent.

0

Hey Ross,

There are a couple options available to you.

The simplest would be to add an additional column to your users_groups pivot table. You would do that like

// User.php

public function groups()
{
    return $this->belongsToMany('Group')->withPivot('role');
}

You would access the data with something like this

$role = $user->groups->first()->pivot('role');

You can read more here (look for 'Retrieving Intermediate Table Columns')

Another option would be to say that a User has many Roles. Essentially, you'd be doing the same thing in your database, your user_groups table would instead be called roles and each record in the table would have it's own id. The table definition would look something like this:

create table roles (
  id int not null auto_increment primary key,
  user_id int not null,
  group_id int not null,
  role varchar(255) not null,
  foreign key fkey_users_user_id (user_id) references users (id),
  foriegn key fkey_groups_group_id (group_id) references groups (id),
  foreign key fkey_roles_role (role) references roles (name)
);

Then the User class would have these relationships:

public function groups()
{
    return $this->belongsToMany('Group', 'roles');
}

public function roles()
{
    return $this->hasMany('Role');
}

You could grab the user, group and role with a query like:

$forGroup = function ($query) use ($groupId)  {
    $query->where('group_id', $groupId);
};

$user = User::with(['groups' => $forGroup, 'roles' => $forGroup])->find($userId);

Hope it helps.

0

Yes, that should do the tick :) Thanks!

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.