Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to display current logged-on user in default.ctp?

I am in the process of customizing the default.ctp file and I am trying to display the currently logged on user's name on the top of the page.

In app_controller.php, I have the following:

function beforeFilter()
{
    $user = $this->Auth->user();

    if($user != null)
    {
        $this->Session->write('user_name',$user['User']['username']);
    }
}

And in default.ctp, I have:

$user = $this->Session->read('Auth.User');

if(!empty($user))
{
    echo 'Hello, ' . $user['user_name'];
}

However, it seems like the value $user_name is not getting set anywhere.

What am I doing wrong? Is there a better way to accomplish this?


Update: I've modified it as described in the answer, but it still doesn't work. I get an error:

Undefined index: user_name [APP/views/layouts/default.ctp, line 21]

like image 383
Nathan Osman Avatar asked Sep 26 '10 23:09

Nathan Osman


2 Answers

you can also use the SessionHelper directly in the view / layout

$user = $this->Session->read('Auth.User');
if(!empty($user)) {
    echo 'Hi ', $user['user_name'];
}
like image 95
dogmatic69 Avatar answered Oct 13 '22 01:10

dogmatic69


Cakephp 2.x:

<?php if (AuthComponent::user('id')): ?>
<p class="navbar-text pull-right">
Logged in as <a href="#" class="navbar-link"><?= AuthComponent::user('name') ?></a>
</p>
<?php endif; ?>
like image 42
Dave Dundee Avatar answered Oct 13 '22 01:10

Dave Dundee