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

Cameron
  • 27,963
  • 100
  • 281
  • 483
  • 1
    If you serve a different view for a different user action (i.e. unauthenticated access), shouldn't you just serve a different view? – kontur Sep 02 '12 at 15:34

13 Answers13

90

You don't need to do $this->set(compact('authUser')); only use this in View:

if ($this->Session->read('Auth.User')){
// do something 
}
meotimdihia
  • 4,191
  • 15
  • 49
  • 69
50

As of CakePHP 2.x:

<?php if (AuthComponent::user('id')): ?>
   Logged in as <?= AuthComponent::user('name') ?>
<?php endif; ?>
jesal
  • 7,852
  • 6
  • 50
  • 56
  • 2
    For CakePHP 3 this causes a fatal error, but `$this->Session->read` gives a deprecated warning with the actual code you should use, as in @LeeNelson's [answer](http://stackoverflow.com/a/29759420/327074) – icc97 Apr 21 '15 at 03:42
31

Note: Also check out meotimdihia's answer below. It's got a lot of upvotes.


The Auth component is for use in the Controller. You'll want to check for authorization in the controller, then set a variable for the view, e.g., $this->set('authUser', $this->Auth->user());. Then in your view you can do:

if (!$authUser)
{
    echo $this->element('header');
}

If you want this to be done automatically for all controller methods, you can look into modifying cake/libs/controller/app_controller.php so that it includes the Auth component.

Community
  • 1
  • 1
webbiedave
  • 48,414
  • 8
  • 88
  • 101
24

To summarize the answers on this page, evaluate one of the following based on which version of CakePHP you are using:

For version 1.x

$this->Session->read('Auth.User')

For version 2.x

AuthComponent::user('id')

For version 3.x

$this->request->session()->read('Auth.User.id')

For version 4.x, using the Authentication component

$this->loadHelper('Authentication.Identity');
...
$this->Identity->isLoggedIn()
Mr Griever
  • 4,014
  • 3
  • 23
  • 41
11

This works in Cakephp 3+ (juts modify: "Auth.User.username" to suit your session data)

<?php

if (is_null($this->request->session()->read('Auth.User.username'))) {

    echo "....logged out";

} else {

    echo "You are Logged in As " . $this->request->session()->read('Auth.User.username'); 

}

?>
Lee Nielsen
  • 111
  • 1
  • 3
  • 5
    I just can't understand why all functions and ways are changing so frequently in cakephp. You learn cake 2.4 then 3.0 comes with all new syntax. Very annoying. – RN Kushwaha May 20 '15 at 12:25
  • 1
    Hey RN Kushwaha, CakePHP follow PHP, there is a PHP 7, did you use all new things in that version? CakePHP 1.x to 2.x make things better only, CakePHP 3 is all new framework made from zero to acomplish to namespaces and all new features in the language. – Newton Pasqualini Filho Aug 11 '16 at 21:33
  • @RNKushwaha the same thing happened to code igniter, laravel and yii.. we have to frequently follow latest technology – aswzen Feb 24 '18 at 19:02
  • @aswzen I understand that but my point is that there must be some wrapper functions that need to be updated. So whenever a change occurs we need to update only that wrapper function. – RN Kushwaha Feb 26 '18 at 05:34
  • 2
    **Attention**, you may have to be using `getRequest()` and `getSession()` as of CakePHP 4+. Either way, gets me *Error: Call to undefined method App\View\AppView::getRequest()* when used from within a layout – ᴍᴇʜᴏᴠ Oct 17 '19 at 13:51
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

Jeremy S.
  • 6,423
  • 13
  • 48
  • 67
2

Try this

class AppController extends Controller{
    $this->user = false;

   public function beforeFilter(){
     $this->user = $this->Auth->user();
   }

   public function beforeRender(){
      $this->set('logged_user',$this->user);
   }
}

Now You can check $logged_user in the view as

if($logged_user){
  // users logged in $logged_user have all the details
}else{
  // not logged in
}
Spandan Singh
  • 674
  • 1
  • 5
  • 15
2

in cakephp 3 you can check authentication session in the view like this

if($this->request->Session()->read('Auth.User')){
//do when login
}
else{
 //do not login
}
Ye Htun Z
  • 2,079
  • 4
  • 20
  • 31
2

If it helps anyone out in cakephp version 3.7.8 session has been depriciated to getSession so to update Lee Nielsen's comment

if (is_null($this->request->getSession()->read('Auth.User.username'))) {

echo "....logged out";

} else {

echo "You are Logged in As " . $this->request->getSession()->read('Auth.User.username'); 

}
infobuster
  • 37
  • 5
2

For cakephp 4.2.6 Strawberry with Auth Component

        <?php 
        // Note: Change email param to yours
        if (is_null($this->request->getSession()->read('Auth')->email)) {
        ?>
            <?= $this->Html->link(__('Login'), [ 'action' => 'login','controller' => 'Users']) ?>
            

        <?php 
        } else { ?>
            <?= $this->Html->link(__('Logout'), [ 'action' => 'logout','controller' => 'Users']) ?>
            
        <?php }
        ?>
        
Zohaib Yunis
  • 376
  • 5
  • 11
0

I found something worth mentioning, In CakePHP 3.x session handler is deprecated,

if we want to access session in view, we can do it via request handler. we have to use

<?php
   // For CakePHP 3.x to access all user information
   $this->request->session()->read('Auth.User');

  // For CakePHP 3.x to check session
  if($this->request->session()->read('Auth.User.id')) {

  }
?>
Amit Sarwara
  • 573
  • 7
  • 15
0

You need to set the user details from a controller, preferably the AppController which is inherited by all controllers across your site. Create/amend your app_controller.php to contain this beforeFilter(); method.

<?php
class AppController extends Controller {

function beforeFilter() {
    $user = $this->Auth->user();
    $this->set(compact('user'));
}

This will set a var called $user to the views which will be empty if the user is not logged in, or contain their data if they are.

Dunhamzzz
  • 14,682
  • 4
  • 50
  • 74
0
//In the views (or layout)
$session->check('Auth.User.id');

//In controller
$this->Auth->User('id'); 
Sumith Harshan
  • 6,325
  • 2
  • 36
  • 35