2

I have 2 models: User and Role. A User belongs to many Roles with a pivot table user_role to link them.

I have three roles: Admin > Manager > Employee.

I would like for:

  1. Managers to view/create/update/delete Employee users only.
  2. Admins to view/create/update/delete any user with any role.

This seems like a common problem but I'm having a hard time making this happen with Laravel policies all within Nova. (This does need to be managed within Nova.)

User model:

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use \App\Role;

class User extends Authenticatable
{
    use Notifiable;

    public function roles()
    {
        return $this->belongsToMany(Role::class)->using('App\RoleUser');
    }

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

Role model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use \App\User;

class Role extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class)->using('App\RoleUser');
    }

}

In my User policy, I'm trying something like the following to only show users who are employees if the authenticated user is a manager.

public function before(User $user, $ability)
{
    if (count($user->roles->whereInStrict('name', 'Admin')) > 0) {
        return true;
    }
}

public function view(User $user, User $user2)
{
    if (count($user->roles->whereInStrict('name', 'Manager')) > 0 && count($user2->roles->whereInStrict('name', 'Employee')) > 0) {
        return true;
    }
    return false;
}

However, this exposes a list of Admins to logged in Managers on the Users resource page. I really don't know whether this is a good approach or not. Do I need to rethink the whole setup? Is there a cleaner/easier way that I don't know about? Again, this must work with Nova. Any suggestions on this would be great, thank you-

Tim Lewis
  • 27,813
  • 13
  • 73
  • 102
Mikesab
  • 21
  • 3

0 Answers0