[英]laravel 8 - Return array based user role
I am using Metronic 8 admin dashboard template for laravel.我正在为 laravel 使用 Metronic 8 管理仪表板模板。
The developer made the nav menu as array:开发人员将导航菜单制作为数组:
<?php
return array(
// Main menu
'main' => array(
//// Dashboard
array(
'title' => 'Dashboard',
'path' => '',
'icon' => theme()->getSvgIcon("demo1/media/icons/duotune/art/art002.svg", "svg-icon-2") ,
) ,
)
)
If you want to add a new nav item, just add an object inside the array.如果要添加新的导航项,只需在数组中添加一个 object 即可。
I am currently using Spatie user roles & permissions.我目前正在使用 Spatie 用户角色和权限。 According to their docs, I can use blade directives like this:
根据他们的文档,我可以像这样使用刀片指令:
@can('permission name')
test
@endcan
OR或者
@role('role name') test @endrole @role('角色名') 测试@endrole
Unfortunately, the menu.php
is a plain php config file and not a blade.不幸的是,
menu.php
是一个普通的 php 配置文件,而不是刀片服务器。 How can I use spatie to hide nav items based on user role?我如何使用 spatie 根据用户角色隐藏导航项?
Resources:资源:
You need to change configs runtime, in Controller or in Middleware or even in Provider, depending on your needs.您需要更改配置运行时,在 Controller 或在中间件中,甚至在提供程序中,具体取决于您的需要。 You need to do something like:
您需要执行以下操作:
$navs = config('config.global.menu');
if(auth()->user()->can('permission name')){
$navs[] = 'nav item';
config([
'config.global.menu' => $navs
]);
}
You can create a new listener and bind Illuminate\Auth\Events\Login
event to it in EventServiceProvider
.您可以在
EventServiceProvider
中创建一个新的侦听器并将Illuminate\Auth\Events\Login
事件绑定到它。 I've named this event as ModifyMetronicMenu
.我将此事件命名为
ModifyMetronicMenu
。
protected $listen = [
Login::class=>[
ModifyMetronicMenu::class
]
];
ModifyMetronicMenu listener ModifyMetronicMenu侦听器
namespace App\Listeners;
class ModifyMetronicMenu
{
public function handle($event)
{
$newMenu = array_filter(config('menu.main'),function ($item){
return \Auth::user()->can(data_get($item,'title'));
});
// Update the menu config file
config(['menu.main'=>$newMenu]);
}
}
As you can see, I have filtered menu and have updated the config.如您所见,我过滤了菜单并更新了配置。 Notice that the condition that I wrote in the
array_filter
is not correct and you should tune it base on your needs.请注意,我在
array_filter
中编写的条件不正确,您应该根据需要调整它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.