Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP3 get user in default.ctp

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?

like image 489
kh.tab Avatar asked Apr 19 '16 10:04

kh.tab


2 Answers

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.

like image 108
floriank Avatar answered Sep 19 '22 13:09

floriank


<?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..

like image 27
Vivek Singh Avatar answered Sep 18 '22 13:09

Vivek Singh