Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP 3.x - AuthComponent::user() in View

In CakePHP 2.x you could do

 AuthComponent::user()

in View to get data from Auth component. In CakePHP 3.0beta3 it throws:

 "Error: Class 'AuthComponent' not found"

Is there a simple way to get data from AuthComponent in View?

like image 993
wildfireheart Avatar asked Dec 19 '14 20:12

wildfireheart


3 Answers

In View:

$this->request->session()->read('Auth.User.username');

In Controller

$this->Auth->user('username');
like image 175
mario741 Avatar answered Nov 08 '22 22:11

mario741


You should have never used the AuthComponent in views in the first place. It is better to either pass down the data from the controller to the view and access that, or better yet, use a AuthHelper to wrapper-access it easily (by reading from the session there for example).

An example would be AuthUser ( https://github.com/dereuromark/cakephp-tools/blob/master/src/View/Helper/AuthUserHelper.php ):

$this->AuthUser->id();
$this->AuthUser->user('username');

etc

The helper way doesn't require additional use statements in your view ctps and keeps them lean. It also prevents notices when trying to access undefined indexed automatically.

if ($this->AuthUser->user('foobarbaz')) { // no error thrown even if it never existed
}
like image 25
mark Avatar answered Nov 08 '22 23:11

mark


Cake 3.5

In AppController:

public function beforeRender(Event $event) {
    ....

    $this->set('Auth', $this->components()->__get('Auth'));
}

In .ctp template:

<?php if (!$Auth->user()) { ?>
    <a class="login" href="<?php echo $this->Url->build($Auth->getConfig('loginAction')); ?>">Login</a>
<?php } else { ?>
    <div class="name"><?php echo h($Auth->user('name')); ?></div>
<?php } ?>
like image 6
AndreyP Avatar answered Nov 08 '22 21:11

AndreyP