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 which tells me to put the current user in session from AppController it doesn't work either.
// in AppController
function beforeFilter(){
$user = $this->Session->read('Auth.User');
$this->set('username', $user['username']);
}
and in default.ctp:
<?=$username?>
How can I make this work?
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.
<?php $session = $this->request->session(); // less than 3.5
// $session = $this->request->getSession(); // 3.5 or more
$user_data = $session->read('Auth.User');
if(!empty($user_data)){
print_r($user_data);
}?>
try this hope it help's..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With