Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access logged in user data, in a layout. (CakePHP 3)

I have a web app programmed in cakephp 3.

I want to have a layout that shows logged in user first & last name. like something in facebook main page. that you can click and go to your page. I want to have this feature in every page, so I decided to use layouts.

my Users table is like:

| id | username | password | email | first_name | last_name | created | modified |

I use Authentication Component like this:

$this->loadComponent('Auth', [
        'loginRedirect' => [
            'controller' => 'Pages',
            'action' => 'display'
        ],
        'logoutRedirect' => [
            'controller' => 'Users',
            'action' => 'login'
        ],
        'authError' => 'Authentication Error'
    ]);

How can I load user first name and last name in a layout?

like image 458
Alireza Avatar asked Dec 19 '22 07:12

Alireza


2 Answers

you can do it by using Session. like:

$user = "";
$loguser = $this->Session->read('Auth.User');
if(!empty($loguser)){
    $user = $loguser['first_name']." ".$loguser['last_name'];
}

UPDATE (8/23/2015) :

as recently cakephp says that SessionHelper is deprecated, you should use request->session() instead.

$loguser = $this->request->session()->read('Auth.User');
if(!$loguser) {
    $user = $loguser['first_name'].' '.$loguser['last_name'];
}
like image 78
Alireza Avatar answered Jan 29 '23 06:01

Alireza


You can pass your variables through controller to views by:

$this->set('user','users_data');

and then pass this to the layout:

$this->assign('user',$user);

and show it in the layout by:

$this->fetch('user');
like image 30
Phaerithm Avatar answered Jan 29 '23 04:01

Phaerithm