kh.tab kh.tab - 7 months ago 63
PHP Question

CakePHP3 get user in default.ctp

Hi i work on CakePHP 3 project..

I want to display username of the logged user from default.ctp so i tried this:

//in default.ctp
$user = $this->Session->read('Auth.User');
if(!empty($user)) {
echo 'Hi ', $user['user_name'];
}


It doesn't work and i found other solution wich tell to put the current user in session from AppController it doesn't work too this is it:

// in AppController
function beforeFilter(){
$user = $this->Session->read('Auth.User');
$this->set('username', $user['username']);
}


and in default.ctp :

<?=$username?>


Can someone help me ?

Answer

Accessing the session is the wrong approach to this. The auth system in CakePHP can handle different sources of the user and the session won't work for stateless auth systems for example.

So the proper approach is to get the user from the abstracted auth system and not reading it directly from the session. Also the session approach will screw up in the case the session key changes.

In the AppController just add this:

public function beforeRender() {
    $this->set('user', $this->Auth->user());
}

Then access the $user var in the view. My plugin even contains a helper to deal with common tasks of the user data in the view.