user1406951
user1406951

Reputation: 446

look up username in view on cakephp

I want to be able to display a user's username with cakephp in my default.ctp view. Using the authComponent I know I can look up the userid, but how can I use this to look up the username from the users table? I'm used to doing this from a controller, I'm not sure how to do it within a view.

users table
userid |  username   

Upvotes: 1

Views: 889

Answers (3)

Josexato
Josexato

Reputation: 50

As of cake 3.6.X this is a sample of what I am using for cake 3 in onder too make a logout buttons that prints the username of the authenticated user

    <?php
        $usert=$this->request->getsession()->read('Auth.User');
    //then you can print the 'username' by
        echo $user['username'];
    ?>

in previous versions of cake these functions were available but now are with deprecation notice:

    $usert=$this->request->session()->read('Auth.User');
    $usert=$this->Session->read('Auth.User');

Upvotes: 0

RpgNick
RpgNick

Reputation: 110

I'm not familiar with CakePHP. But in any MVC framework, you should never access the database from your view. The correct way to handle this is to have the Controller tell the View which data (which is usually from a Model) to display.

For more information about MVC within CakePHP, check here.

Upvotes: 1

Hoff
Hoff

Reputation: 1772

If you already know how to do it within a controller - then you're done 99% of the battle. You just need to pass your user that you retrieved in the controller to the view.

In your controller:

$user = $this->User->read(null, $this->Auth->user('id'));
$this->set('user', $user);

In your view:

<?php echo $user['User']['username']; ?>

This is very basic Cake stuff, you should spend a little more time on the manual :)

Upvotes: 2

Related Questions