3

How can I get currently online user data with all the parameters from the database? Right now I get it's ID by using this:

echo Yii::$app->user->getId();

Can I reach other data somehow or do I have to create a function which gets all the information by the user ID?

The50
  • 1,096
  • 2
  • 23
  • 47

3 Answers3

3

You can access to all the identity values in this way

this for username

Yii::$app->user->identity->username

check for your User models for others attributes

http://www.yiiframework.com/doc-2.0/guide-security-authentication.html

http://www.yiiframework.com/doc-2.0/yii-web-identityinterface.html

http://www.yiiframework.com/doc-2.0/yii-web-user.html

(and your User model of course)

ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
3

You can access the model of the currently logged in user with:

$user = Yii::$app->user->identity;

This will return either null (if the user is not logged in) or an instance of the identityClass you defined for the user component in your config. Ex:

'user' => [
    'identityClass' => 'app\models\User',
    'enableAutoLogin' => true,
],

So you can use it like any other model class and access it's attributes and/or methods. Just make sure you configure correctly the user component and the identityClass exists and can be accessed.

marche
  • 1,756
  • 1
  • 14
  • 24
0

current user is:

Yii::$app->user->identity

it can be null, so check it before accessing fields

csminb
  • 2,382
  • 1
  • 16
  • 27