Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 isGuest giving exception in console application

In console application when I used Yii::$app->user->isGuest it is giving the below exception:

Exception 'yii\base\UnknownPropertyException' with message 'Getting unknown prop
erty: yii\console\Application::user'

I even tried adding the user in components array in config file. But it didn't worked. Any idea what am I doing wrong?

like image 952
Chinmay Waghmare Avatar asked Oct 09 '15 11:10

Chinmay Waghmare


2 Answers

In Console application Yii->$app->user does not exist. So, you need to configure user component in config\console.php.

like as,

config\console.php

 'components' => [
 .........
 ......
        'user' => [
            'class' => 'yii\web\User',
            'identityClass' => 'app\models\User',
            //'enableAutoLogin' => true,
        ],
        'session' => [ // for use session in console application
            'class' => 'yii\web\Session'
        ],
 .......
]

To check it works or not using below code.

public function actionIndex($message = 'hello world')
{
    echo $message . "\n";
    $session = \Yii::$app->session->set('name', 'ASG');

    if(\Yii::$app->session) // to check session works or not
        echo \Yii::$app->session->get('name')."\n";

    print_R(\Yii::$app->user);
}

More info about your problem : Link

Note : There's no session in console.

like image 190
GAMITG Avatar answered Nov 12 '22 17:11

GAMITG


The reason is simple. Guide says about application components (user is a component):

user: represents the user authentication information. This component is only available in Web applications Please refer to the Authentication section for more details.

So Yii::$app->user it not available in console applications.

As a consequence you have to consider using this component in model classes that are also used by console applications.

Extra note: it is internally used by BlameableBehavior, however, this makes no problems since user will be null if a model gets saved/created and no user is available.

like image 20
robsch Avatar answered Nov 12 '22 17:11

robsch