Wednesday, January 5, 2022

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

Issue

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?


Solution

Cake 3.5

In AppController:

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

    $this->set('Auth', $this->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 } ?>


Answered By - AndreyP

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.