Skip to content
Advertisement

Yii 2 Menu Display List Depending on User

How do I configure or customize my Menu where in, for example, if I am an admin user, I can see everything on my navigation bar, like, in my case, the Users (list of Users where I can create, update, or delete one), Stores (just like Users, this is where I can configure a specific store), Transactions and then the Logout button. But when an ordinary user/staff logs in, the only thing he/she will see is the Transactions menu and a Logout button as well.

Please help.

Edit: Here is my menu rendering code:

<?php
    echo Menu::widget([
        'options' => ['id' => "nav-mobile", 'class' => 'right side-nav'],
        'items' => [
          ['label' => 'Home', 'url' => ['/site/index']],
          ['label' => 'About', 'url' => ['/site/about']],
          ['label' => 'Contact', 'url' => ['/site/contact']],
          Yii::$app->user->isGuest ?
              ['label' => 'Login', 'url' => ['/site/login']] :
              ['label' => 'Logout (' . Yii::$app->user->identity->username . ')',
                  'url' => ['/site/logout'],
                  'linkOptions' => ['data-method' => 'post']
              ],
      ],
    ]);
?>

Advertisement

Answer

Each item in items array has visible property. Pass expression returning boolean value there.

'items' => [
    // Show users section for administrators only
    [
        'label' => 'Users',
        'url' => ['/users/index'],
        'visible' => !Yii::$app->user->isGuest && Yii::$app->user->identity->user_type == User::USER_TYPE_SUPER_ADMIN,
    ],
],

Yoy can also put this condition in additional model method to avoid repeating, something like isAdmin() in User model.

Official documentation:

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement