Reputation: 494
My variable loggedIn
is defined in my AppController
in the beforeFilter()
function, as follows:
function beforeFilter(){
$this->Auth->loginRedirect = array('controller'=> 'questions', 'action' => 'home');
$this->Auth->logoutRedirect = array('controller'=> 'questions', 'action' => 'home');
$this->Auth->allow('signup', 'confirm', 'home', 'show');
$this->Auth->authorize = 'controller';
$this->Auth->userScope = array('User.confirmed' => '1');
$this->set('loggedIn', $this->Auth->user('id'));
}
In my layout, I am testing the value of the loggedIn
variable using the following:
<?php if($loggedIn): ?>
When I run the application I get this error:
Undefined variable: loggedIn [APP\View\Layouts\default.ctp
Can you help me? Thank you in advance.
Upvotes: 1
Views: 4327
Reputation: 2776
There is a better way to do this.
In your AppController:
public function beforeFilter() {
parent::beforeFilter();
$this->set('loggedIn', $this->Auth->loggedIn());
}
Or, if you need to access the loggedIn var in your controllers and your views:
public function beforeFilter() {
parent::beforeFilter();
$loggedIn = $this->Auth->loggedIn();
$this->set('loggedIn', $loggedIn);
}
Why is this in beforeFilter()? So that the variable is accessible before preparing the page. This returns a Boolean, perfect for deciding if a user is logged in or not, so evaluate it as:
<?php if($logged_in===true): ?>
If you do still need the user ID or other user attributes, then use this in your view:
$id = $this->Auth->user('id');
You wouldn't set individual attributes in beforeFilter if they can already be accessed in your view - you want to keep controllers as skinny as possible.
Upvotes: 2
Reputation: 1625
function beforeFilter(){
parent::beforeFilter();
$this->Auth->loginRedirect = array('controller'=> 'questions', 'action' => 'home');
$this->Auth->logoutRedirect = array('controller'=> 'questions', 'action' => 'home');
$this->Auth->allow('signup', 'confirm', 'home', 'show');
$this->Auth->authorize = 'controller';
$this->Auth->userScope = array('User.confirmed' => '1');
$this->set('loggedIn', $this->Auth->user('id'));
}
Change you beforeFilter function add line parent::beforeFilter();
, after that in layout file you can use <?php if($loggedIn): ?>
Upvotes: 0