Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print the username using session in cakephp?

I cannot get my username to show on the website when I call it form the session.

The code on the index page is:

<h1>Users Home</h1>
Welcome <?php $user = $this->Session->read('Users.username');?>

What am I doing wrong?

I've also tried various other ways of calling it and then getting different error messages.

like image 296
iwj145 Avatar asked May 02 '26 15:05

iwj145


2 Answers

In your code you are setting $user with the content of the username. But you are not printing it.

<h1>Users Home</h1>
Welcome <?=$this->Session->read('Auth.User.username')?>

which is short for

<h1>Users Home</h1>
Welcome <?php print $this->Session->read('Auth.User.username'); ?>
like image 65
Hugo Delsing Avatar answered May 04 '26 03:05

Hugo Delsing


As Hugo said you should do the following:

<h1>Users Home</h1>
Welcome <?php echo $this->Session->read('Auth.User.username'); ?>

If you are going to use it on more than one view, I would suggest you to add the following on AppController.

public function beforeFilter() {
    $this->set('username', AuthComponent::user('username'));
    // OR $this->set('username', $this->Session->read('Auth.User.username'));
}

And then on any of your view just use the variable $username to print the current username.

<?php echo $username; ?>
like image 43
Domingo C. Avatar answered May 04 '26 04:05

Domingo C.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!