Navbar visibility based on user permission using RBAC

I am trying to achieve the navbar visibility for a specified user it was working fine when I logged in, the navbar visibility was working until when I logged out there was this error:

Undefined variable: $items

this is where the error is

echo Nav::widget([
‘options’ => [‘class’ => ‘navbar-nav navbar-right’],
‘items’ => $items,
]);

Hi @atif, welcome to the forum!

Could you show us the code that runs before these lines, where $items are defined according to the user permission?

Most probably you have to add

$items = [];

somewhere in your code in order to deal with the permissions of a guest user.

Thank you for your reply. Sorry im new in yii, i will really appreciate your help.
This is the code before these lines:

$navItem = [

];

$itemsForAdmin = [
[‘label’ => ‘Home’, ‘url’ => [‘addproduct/index’]],
[‘label’ => ‘User’, ‘url’ => [‘new-user/index’]],
];

$landr = [
[‘label’ => ‘Login’, ‘url’ => [’/site/login’]],
[‘label’ => ‘Register’, ‘url’ => [’/site/register’]],
];

$items = ArrayHelper::merge($navItem, $itemsForAdmin);

if(Yii::$app->user->isGuest){
array_push($navItem, $landr);
}

else {
array_push($navItem, ‘

  • ’. Html::beginForm([’/site/logout’], ‘post’). Html::submitButton(‘Logout (’ . Yii::$app->user->identity->username . ‘)’,[‘class’ => ‘btn btn-link logout’]).Html::endForm(). ‘
  • ’);
    }

    if (Yii::$app->user->can(‘admin’)) {
    return $items;
    }

    echo Nav::widget([
    ‘options’ => [‘class’ => ‘navbar-nav navbar-right’],
    ‘items’ => $items,
    ]);
    NavBar::end();
    ?>

    It looks a bit confused.

    Try this instead:

    $navItem = [
        ...
    ];
    
    $itemsForAdmin = [
        ['label' => 'Home', 'url' => ['addproduct/index']],
        ['label' => 'User', 'url' => ['new-user/index']],
    ];
    
    $landr = [
        ['label' => 'Login', 'url' => ['/site/login']],
        ['label' => 'Register', 'url' => ['/site/register']],
    ];
    
    if (Yii::$app->user->can('admin')) {
        array_push($navItem, $itemsForAdmin);
    }
    
    if(Yii::$app->user->isGuest){
        array_push($navItem, $landr);
    } else {
        array_push($navItem, '<li>'. Html::beginForm(['/site/logout'], 'post'). 
            Html::submitButton('Logout (' . Yii::$app->user->identity->username . ')', 
           ['class' => 'btn btn-link logout']).Html::endForm(). '</li>');
    }
    
    echo Nav::widget([
        'options' => ['class' => 'navbar-nav navbar-right'],
        'items' => $navItem,
    ]);
    NavBar::end();
    
    1 Like

    Thank you very much!:slightly_smiling_face: It Worked!!!