Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if user is logged in using CakePHP

Tags:

php

cakephp

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?

like image 612
James Dawson Avatar asked Dec 04 '22 03:12

James Dawson


2 Answers

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());
}
like image 89
teknix Avatar answered Dec 29 '22 23:12

teknix


Try using:

if ($this->Auth->loggedIn()) {
like image 28
Hoff Avatar answered Dec 30 '22 01:12

Hoff