Kiruaaa
Kiruaaa

Reputation: 301

Cakephp 4 - Authentication Plugin how to fetch current user name?

I'm using CMS Authentication plugin

I fetch current user name like this but when I update user profile the current user name doesn't get reflected I need to logout first

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

Upvotes: 0

Views: 528

Answers (1)

Salines
Salines

Reputation: 5767

How to @ CakePHP 4.x

update identity object with: $this->Authentication->setIdentity($user);

Full example:

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'));
}

Upvotes: 1

Related Questions