CakePHP check if user is logged in inside a view

You don't need to do $this->set(compact('authUser')); only use this in View:

if ($this->Session->read('Auth.User')){
// do something 
}

As of CakePHP 2.x:

<?php if (AuthComponent::user('id')): ?>
   Logged in as <?= AuthComponent::user('name') ?>
<?php endif; ?>

Note: Also check out meotimdihia's answer below. It's got a lot of upvotes.


The Auth component is for use in the Controller. You'll want to check for authorization in the controller, then set a variable for the view, e.g., $this->set('authUser', $this->Auth->user());. Then in your view you can do:

if (!$authUser)
{
    echo $this->element('header');
}

If you want this to be done automatically for all controller methods, you can look into modifying cake/libs/controller/app_controller.php so that it includes the Auth component.

Tags:

Php

Cakephp