1

I've been trying to get the user id when running a task to save it on a table but cannot find a way to get it not even the user info.

Using Craft::$app->getUser() or Craft::$app->user I get:

["_identity":"craft\console\User":private]=>
  bool(false)
["_events":"yii\base\Component":private]=>
  array(0) {
}
["_eventWildcards":"yii\base\Component":private]=>
  array(0) {
}
["_behaviors":"yii\base\Component":private]=>
NULL

which is not good and if I try with Craft::$app->getUser()->getIdentity() I get an error.

Is there a way to get the user information within a task?.

Thank you for all your help!

1
  • What is the error you're getting?
    – MoritzLost
    Apr 29 at 9:18

2 Answers 2

2

Are you running this task as part of a web request or a console request? The craft\console\User indicates that it's a console request. For console requests, there's no current user, as the console command isn't associated with any session or user account. In this case, you're gonna have to use a user query to find the user account you want to save info on:

use craft\elements\User;

// add whatever conditions you want
$user = User::find()->id(123)->one();

For a web request Craft::$app->getUser()->getIdentity() is the correct way to get the current user. If it's returning null, it means the current request is performed by a guest, so there's no current user.

2

If you know the user ID at the point the task is created, you can pass it in as a property of the task class. Here's an example queue task class:

class myQueueJob extends BaseJob
{

    // Public Properties

    /** @var string */
    public $userId;

    // Public Methods

    /**
     * @param QueueInterface|Queue $queue
     * @return mixed|void
     * @throws Exception
     */
    public function execute($queue)
    {
        $user = Craft::$app->getUsers()->getUserById($this->userId);

        // Do queue job stuff
    }
}

When the task is created, the user ID can be passed in. For example, this would pass in the user ID of the current user, assuming the code was executed as part of a web request:

// Get current user
$user = Craft::$app->getUser()->getIdentity()

Craft::$app->getQueue()->delay(0)->push(new 
    myQueueJob([
        'userId' => $user->id
    ])
);

You could look the user up by ID, rather than using the current user, or even pass in a static ID.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.