Getting unknown property: yii\web\User::admin

Viewed 249

I am quite new to Yii 2 and I am trying to hide some navbar items from users that are not admins. However, I somehow get an error stating that the User model has no such property called admin.

I am confused since the model has an attribute called admin with a boolean value. I have been searching on different websites but I can't seem to find a solution so far. Whenever I login as a User, no matter if it's an admin or not, the navbar items are shown.

Below is what I am trying to do in the main.php

<header>
    <?php
    NavBar::begin([
        'brandLabel' => Yii::$app->name,
        'brandUrl' => Yii::$app->homeUrl,
        'options' => [
            'class' => 'navbar navbar-expand-md navbar-dark bg-dark fixed-top',
        ],
    ]);
    echo Nav::widget([
        'options' => ['class' => 'navbar-nav'],
        'items' => [
            ['label' => 'Home', 'url' => ['/site/index']],
            ['label' => 'About', 'url' => ['/site/about']],
            ['label' => 'Contact', 'url' => ['/site/contact']],
            ['label' => 'Team', 'url' => ['/team/index'], 'visible' => Yii::$app->user->admin ? true : false],
            ['label' => 'User', 'url' => ['/user/index'], 'visible' => Yii::$app->user->admin ? true : false],
            Yii::$app->user->isGuest ? (
                ['label' => 'Login', 'url' => ['/site/login']]
            ) : (
                '<li>'
                . Html::beginForm(['/site/logout'], 'post', ['class' => 'form-inline'])
                . Html::submitButton(
                    'Logout (' . Yii::$app->user->identity->username . ')',
                    ['class' => 'btn btn-link logout']
                )
                . Html::endForm()
                . '</li>'
            )
        ],
    ]);
    NavBar::end();
    ?>
</header>

I am not understanding why Yii::$app->user->adminis not working.

I have tried Yii::$app->user->getIdentity('admin') as well but it's not working either. As I said above, the User model does have an attribute called admin with a boolen value.

Any help is greatly appreciated.

1 Answers

That's because Yii::$app->user is not instance of your user model. It's instance of yii\web\User component.

If you've followed the guide, you've made your User model implement yii\web\IdentityInterface and set the model class as identityClass then you can access the user model as Yii::$app->user->identity or Yii::$app->user->getIdentity().

So, to access the admin property of user model you have to do Yii::$app->user->identity->admin or Yii::$app->user->getIdentity()->admin.

Related