Alex Rivera | Logout

CakePHP check if user is logged in inside a view

Asked 2011-05-05T17:17:35.793
27

I have the following code:

    <?php

    if (!$this->Auth->user())
    {
        echo $this->element('header');
    }
    else
    {
        echo $this->element('header-bar');
    }

    ?>

inside my view which should show a different header for logged in users but throws the following error:

Notice (8): Undefined property: View::$Auth [APP/views/layouts/page.ctp, line 17]
Fatal error: Call to a member function user() on a non-object in /Users/cameron/Sites/thehive/app/views/layouts/page.ctp on line 17

How do I fix this? Thanks

Edit
Report

1 Answer

5

its been a while that I have used CakePHP but as far as I can remember CakePHP doesn't support Auth in View. What you can do of course is set a variable in the controller to use it in the view

<?
   class AppController {
     ....
     function beforeFilter(){
       ....
       $this->set('auth',$this->Auth);
     }
     ....
   }
?>

and then use it in the view like this

$auth->....

or you can use the AuthHelper written by Ritesh Agrawal

http://bakery.cakephp.org/articles/ragrawal/2008/07/29/authhelper

BTW

I think if it comes to only test if somebody is logged in @webbiedave's answer is better MVC style wise.

Nevertheless if you have to access userdata in view the just extract the userinfo from Auth component and set it in the controller as I showed you and use it in the view

Regards

answered 2011-05-05T17:26:46.327

Your Answer