From 6e9cfb4108ff1e1cf894a0321d1160eec4a95b44 Mon Sep 17 00:00:00 2001 From: Bayu Hendra Winata Date: Tue, 26 Nov 2019 11:33:44 +0700 Subject: [PATCH] add: filter menu by roles --- src/Menu.php | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/src/Menu.php b/src/Menu.php index e283efe..a87aa3a 100644 --- a/src/Menu.php +++ b/src/Menu.php @@ -59,23 +59,31 @@ public function all() protected function filterByVisibility(Item $item) { $permission = $item->data('permission'); + $roles = $item->data('roles'); + $permissionCheck = $rolesCheck = true; - // If menu doesn't define permission, we assume this menu visible to everyone - // Otherwise, check if current user has access - if ($permission === null) { - return true; + if ($roles) { + $rolesCheck = auth()->user()->hasRole($roles); } - // If it was multiple permissions, we check using OR conditions. - // It means, user only need to have one of the permissions - if (is_array($permission)) { - foreach ($permission as $perm) { - if (auth()->user()->can($perm)) { - return true; + // If permission defined, we assume User doesn't allowed to access Menu, + // until she proved that she has the access + if ($permission) { + $permissionCheck = false; + // If it was multiple permissions, we check using OR conditions. + // It means, user only need to have one of the permissions + if (is_array($permission)) { + foreach ($permission as $perm) { + if (auth()->user()->can($perm)) { + $permissionCheck = true; + break; + } } + } else { + $permissionCheck = auth()->user()->can($item->data('permission')); } } - return auth()->user()->can($item->data('permission')); + return $permissionCheck && $rolesCheck; } }