首页 > 解决方案 > Cakephp 4 - 身份验证插件如何获取当前用户名?

问题描述

我正在使用 CMS 身份验证插件

我像这样获取当前用户名,但是当我更新用户配置文件时,当前用户名没有得到反映我需要先注销

    $user = $this->request->getAttribute('identity');
    $name = $user->first_name ?? '';

标签: phpcakephp

解决方案


如何@ CakePHP 4.x

更新身份对象:$this->Authentication->setIdentity($user);

完整示例:

public function editMe()
{
    // fetch current identity data
    $user = $this->Authentication->getIdentity()->getOriginalData();
    if ($this->request->is(['patch', 'post', 'put'])) {
        $user = $this->Users->patchEntity($user, $this->getRequest()->getData());
        if ($this->Users->save($user)) {
            $this->Authentication->setIdentity($user); // ----- > update identity data
            $this->Flash->success(__('The user has been saved.'));

            return $this->redirect(['action' => 'me']);
        }
        $this->Flash->error(__('The user could not be saved. Please try again.'));
    }
    $this->set(compact('user'));
}

推荐阅读