Patricia
Patricia

Reputation: 2865

Get the name of the user in yii2

How can I get the name of the logged-in-user in yii2? I can get the user-id with

Yii::$app->user->id;

and I know that I could find the name in the database but I want a direct way. The name-column in the database has the name "username", but

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

doesn't work and

Yii::$app->user->name;     

doesn't work either.

Upvotes: 30

Views: 78144

Answers (5)

Amjad A Shah
Amjad A Shah

Reputation: 45

I always prefer below code to find current user. use only this and you will get the identity.

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

Upvotes: 0

code-droid
code-droid

Reputation: 322

$user_id = Yii::$app->user->id;
$user_name = User::find()->where(['id'=>$user_id])->one()->username;

Upvotes: 1

rizesky
rizesky

Reputation: 444

Easy, just use:

<?= \Yii::$app->user->identity->username ?>

Upvotes: 5

CyberPunkCodes
CyberPunkCodes

Reputation: 3777

While the answer from @thepeach works, you can actually extend the User component and add your own functions, so that you can get them via Yii::$app->user->something as you were initially trying to do.

I like to extend things like this from the start, so I am ready to add custom functionality without having to refactor any code. It sucks to do things one way, then have to go back and fix 100 spots of code, because you changed it later.

First, define a user component class in your config:

'components' => [
    'user' => [
        'class' => 'app\components\User', // extend User component
    ],
],

Then create User.php in your components directory. If you haven't made this directory, create it in your app root.

User.php

<?php
namespace app\components;

use Yii;

/**
 * Extended yii\web\User
 *
 * This allows us to do "Yii::$app->user->something" by adding getters
 * like "public function getSomething()"
 *
 * So we can use variables and functions directly in `Yii::$app->user`
 */
class User extends \yii\web\User
{
    public function getUsername()
    {
        return \Yii::$app->user->identity->username;
    }

    public function getName()
    {
        return \Yii::$app->user->identity->name;
    }
}

Now you can access these through Yii::$app->user->something.

For example, put this in one of your views and access the page in your browser:

<?= \Yii::$app->user->username ?>

I wrote a more detailed answer here, which covers this a bit more in depth.

Upvotes: 12

Mr Peach
Mr Peach

Reputation: 1364

On login the user information will be stored in Yii::$app->user->identity variable.

For more information have a read through the User Authentication documentation in the official guide.

Upvotes: 50

Related Questions