Thursday, 20 February 2014

CakePHP: How to check user loggedIn or not in View Helper

For past few days, i am working on CakePHP Projects. I need to to verify whether user loggedIn or not in the CakePHP view files. In order to achieve this, i need to access Auth Component in View Helper. But CakePHP doesn't have AuthViewHelper Class by default. So i added an helper method  isLoggedIn() which will check whether User loggedIn or not. Here is the implementation code.

class AppHelper extends Helper {

    public $helpers = array("Session");

    /**
     * check user logged or not
     */

    public function isLoggedIn() {

        if ($this->Session->read('Auth.User') !== null) {
            return true;
        }

        return false;
    }
}

This method isLoggedIn() is placed inside AppHelper Class, so this method will be available for all view helpers. User login informations will be stored in PHP Session key 'Auth.User',  when user logged in using Login Form and these session details will be accessed using Session Helper ($this->Session).

Inorder to access the above view helper method  isLoggedIn() in view files. here is the code.

$this->Html->isLoggedIn()

Hope, you enjoyed this Post.

No comments:

Post a Comment