简体   繁体   中英

How to get results In laravel multiple one to many relationship get data based on roles of a user

I am creating a custom ACL according to my requirements. but stuck in between i have attached a Database design where user can belong to only one department and can have only one role of that department but can have multiple permissions in that department. but now when i tried to get permissions against a role of the user but shows me an empty array where in database right entries are made.

Controller Method in controller where is dd($data['getUserRoles']); returns me the following result empty array of permissions how can get list of permissions assigned to a particular role.

 public function index()
{

    $user = new User();

    $user_id = Auth::id();

    $admin_user = $user->isAdmin();

    $assigned_roles = array();

    if (!$admin_user) {

        $data['getUserRoles'] = User::with('roles', 'permissions')->where('users.id', $user_id)->get();


        dd($data['getUserRoles']);

        foreach($data['getUserRoles'][0]->roles as $roles){

            $assigned_roles[] =  $roles->slug;
        }

        $data['assigned_roles'] = $assigned_roles;

        $data['departments'] =  Department::all();

    } elseif ($admin_user) {

        $data['getUserRoles'] = $user->getUserWithRoles();

        $data['departments'] =  Department::all();
    }

    $data['status'] =  array('Active', 'Inactive', 'Blocked');

    return view('users.users_list', $data);
}

Result

Illuminate\Database\Eloquent\Collection {#381 ▼
#items: array:1 [▼
  0 => App\User {#374 ▼
   #fillable: array:7 [▶]
   #hidden: array:2 [▶]
   #casts: array:1 [▶]
   #connection: "mysql"
   #table: "users"
   #primaryKey: "id"
   #keyType: "int"
   +incrementing: true
   #with: []
   #withCount: []
   #perPage: 15
   +exists: true
   +wasRecentlyCreated: false
   #attributes: array:12 [▶]
   #original: array:12 [▼
    "id" => 24
    "name" => "sana"
    "email" => "sana@mailinator.com"
    "email_verified_at" => null
    "password" => "$2y$10$NNtg6ikyKEijQmW1ZDvBE.OMVaFs7ZEj6qmpbr7h6uk/6Vjqq3NBu"
    "remember_token" => null
    "created_at" => "2020-01-30 08:27:48"
    "updated_at" => "2020-01-30 08:29:43"
    "full_name" => null
    "status" => "Active"
    "department_id" => 1
    "manager_id" => null
  ]
  #changes: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: array:2 [▼
    "roles" => Illuminate\Database\Eloquent\Collection {#380 ▼
      #items: array:1 [▼
        0 => App\Models\Role {#378 ▼
          #connection: "mysql"
          #table: "roles"
          #primaryKey: "id"
          #keyType: "int"
          +incrementing: true
          #with: []
          #withCount: []
          #perPage: 15
          +exists: true
          +wasRecentlyCreated: false
          #attributes: array:5 [▶]
          #original: array:7 [▶]
          #changes: []
          #casts: []
          #dates: []
          #dateFormat: null
          #appends: []
          #dispatchesEvents: []
          #observables: []
          #relations: array:1 [▶]
          #touches: []
          +timestamps: true
          #hidden: []
          #visible: []
          #fillable: []
          #guarded: array:1 [▶]
        }
      ]
    }
    "permissions" => Illuminate\Database\Eloquent\Collection {#369 ▼
      #items: []
    }
  ]
  #touches: []
  +timestamps: true
  #visible: []
  #guarded: array:1 [▶]
  #rememberTokenName: "remember_token"
}
]
}

User Model

class User extends Authenticatable
{
 public function getUserWithRoles(){

    $getUserWithRoles = User::with('roles', 'permissions')->get();

    return $getUserWithRoles;
}

public function isAdmin(){

    return Auth::user()->roles()->where('name', 'admin')->exists();
}

public function department()
{
    return $this->belongsTo('App\Models\Department');
}
public function givePermissionsTo($permissions) {
    $permissions = $this->getAllPermissions($permissions);
    if($permissions === null) {
        return $this;
    }
    $this->permissions()->saveMany($permissions);
    return $this;
}

public function withdrawPermissionsTo($permissions) {
    $permissions = $this->getAllPermissions($permissions);
    $this->permissions()->detach($permissions);
    return $this;
}

public function deletePermissions($permissions) {
    $permissions = $this->getAllPermissions($permissions);
    $this->permissions()->detach($permissions);
    return $this;
}

public function refreshPermissions($permissions) {
    $this->permissions()->detach();
    return $this->givePermissionsTo($permissions);
}

protected function hasPermissionTo($permission) {
    return $this->hasPermissionThroughRole($permission) || $this->hasPermission($permission);
}

public function hasPermissionThroughRole($permission) {
    foreach ($permission->roles as $role){
        if($this->roles->contains($role)) {
            return true;
        }
    }
    return false;
}

public function hasRole( $roles ) {

    foreach ($roles as $role) {
        if ($this->roles->contains('slug', $role)) {
            return true;
        }
    }
    return false;
}

public function roles() {
    return $this->belongsToMany(Role::class,'users_roles');

}
public function permissions() {
    return $this->belongsToMany(Permission::class,'users_permissions');

}

protected function hasPermission($permission) {
    return (bool) $this->permissions->where('slug', $permission->slug)->count();
}

protected function getAllPermissions(array $permissions) {
    return Permission::whereIn('slug',$permissions)->get();
}

}

Role Model

class Role extends Model
{

public function permissions() {
    return $this->belongsToMany(Permission::class,'roles_permissions');
}


public function allRoles(){

    $all_roles = Role::leftJoin('roles_permissions', function($join) {
        $join->on('roles.id', '=', 'roles_permissions.role_id');
    })
        ->get();

    return $all_roles;
}

public function user() {
    return $this->belongsToMany(User::class, 'users_roles');
}

public function roles() {
    return $this->belongsToMany(Role::class,'roles_permissions');

}

}

how to get user?! you create a user model but it is empty because you create a new model of User but get it from database

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM