Get userdetails in template view

I’m trying to get the userdetails (at the moment just the firstname and the lastname) from the currently logged in user.
However, these details are not stored in the same table as the login details (username, email and password).
This is how my schema looks (please ignore the fact that I use a 1:n relation, this is now a 1:1 relation):

I’m trying to get the firstname and the lastname into my view (nav.ctp) which is currently loaded into the template using <?= $this->element('nav') ?> in the Template/Layout/default.ctp file.

how do you get user from your database?

Currently, they login on the login page, and the content from the users table gets put into the session (with the exception of the password hash of course).
currently I don’t get the users_details contents at all because I want this to be fetched when the user loads the page instead of having to re log.
this then has to be loaded and echo’ed into the nav.ctp in a specific spot (which says Welcome, <firstname + lastname>).

I added this code to my AppController.php:

  $user_details = $this->UsersDetails->find(
      'conditions' => array(
        'id' => $this->request->getSession()->read('Auth.User')['id']

And this to my nav.ctp:

<?php if($this->request->getSession()->read('Auth.User')){ ?>
  <a class="dropdown-item" href="#">Welcome, <?= htmlentities($this->request->getSession()->read('Auth.UserDetails')[0]->firstname); ?></a>
<?php } else { ?>
  <a class="dropdown-item" href="/login">Login</a>
  <a class="dropdown-item" href="/register">Register</a>
<?php } ?>

This seems to have done the trick :slight_smile:
It might not be the cleanest solution (I think?), but for now I can continue.
If somebody has advice for me on how to do this better, then feel free to add that to the thread

few pointers to your code (hope you wont get me as a picky one :wink: )

$this->request->getSession()->read('Auth.User') is the same as $this->Auth->user() you can also get fields from user when adding argument to is like $this->Auth->user('id')

instead of $this->request->getSession()->read('Auth.User') in view template its better to set user in controller

$this->set('loggedIn', $this->Auth->user());

//in template
if ($loggedIn) { ...

htmlentities in cake you have shothand h function i.e. echo h($loggedIn['username']);

try to familiarize yourself with cake instead of

<a class="dropdown-item" href="/login">Login</a>


<?= $this->Html->link('Login', ['controller' => 'Users', 'action' => 'login'], ['class' => 'dropdown-item']) ?>

this ways if your route changes in future it will be adjusted automaticly

1 Like

Thanks for the feedback, I’ll change this right away :slight_smile:
I knew about the Html helpers but I just keep forgetting them (still have to get used to it).