Home > Software engineering >  laravel 8 - Return array based user role
laravel 8 - Return array based user role

Time:03-14

I am using Metronic 8 admin dashboard template for laravel.

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.

I am currently using Spatie user roles & permissions. According to their docs, I can use blade directives like this:

@can('permission name')
test
@endcan

OR

@role('role name') test @endrole

Unfortunately, the menu.php is a plain php config file and not a blade. How can I use spatie to hide nav items based on user role?

Resources:

Metronic laravel docs
Spatie docs

CodePudding user response:

You need to change configs runtime, in Controller or in Middleware or even in Provider, depending on your needs. 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
    ]);
}

CodePudding user response:

You use AppServiceProvider or create a new service provider and override config file in it according to your application's conditions. You should add these changes in boot() method of the service provider as it will be executed after all config files loaded.

Below code may help you

$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.

  • Related