Я создаю собственный ACL в соответствии с моими требованиями. но застрял между ними, я прикрепил дизайн базы данных, где пользователь может принадлежать только одному отделу и может иметь только одну роль этого отдела, но может иметь несколько разрешений в этом отделе. но теперь, когда я пытался получить разрешения для роли пользователя, но показывает мне пустой массив, где в базе данных сделаны правильные записи.
Метод контроллера в контроллере, где dd($data['getUserRoles']);
возвращает мне следующий результат пустой массив Как получить список разрешений, назначенных для определенной роли.
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);
}
Результат
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"
}
]
}
Модель пользователя
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();
}
}
Ролевая модель
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');
}
}