I want to display a different navigation bar to my users based on if they're logged in or not. I have handled the registration and logging in stage, but having trouble checking if the users are logged in and displaying the correct navigation bar.
This is what I have in AppController.php
:
public $components = array('Session', 'Auth' => array(
'loginRedirect' => array('controller' => 'users', 'action' => 'account'),
'logoutRedirect' => array('controller' => 'pages', 'action' => 'home')
));
public $loggedIn = false;
public function beforeFilter() {
$this->Auth->allow('home', 'register', 'login');
if ($this->Auth->user('id')) {
$this->set('loggedIn', true);
}
}
and then in my layout (not view):
<?php if ($loggedIn): ?>
logged in
<?php else: ?>
<li class="right"><a href="/register">Register</a></li>
<li class="right"><a href="/login">Login</a></li>
<?php endif; ?>
However, $loggedIn
is always false. If do $this->set('loggedIn', $this->loggedIn);
from within my individual controllers it works fine, but in an attempt to keep my code DRY I only want it in the controller that all my other controllers inherit from (AppController
).
Is there an easy way to do this that i'm missing?
I know this has already been answered but I will post my findings anyway..
The way I solved this issue and made $loggedIn globally available was adding it to the AppController.php file in beforeFilter()
public function beforeFilter() {
$this->set('loggedIn', $this->Auth->loggedIn());
}
Try using:
if ($this->Auth->loggedIn()) {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With