user1183721
user1183721

Reputation: 135

Cakephp 2 - check if a user is logged in view

I need a display element according to whether the user is logged or not - In CakePHP 2.0

This does not work

<?php
  if ($this->Auth->loggedIn() 
    { 
    echo $this->element('user');
    }

  else 
    {
    echo $this->element('guest');
    } 
?>

Thanks

Upvotes: 4

Views: 9346

Answers (4)

Dharmendra
Dharmendra

Reputation: 127

!$this->Session->check('marketplace_showlink'

if error occures in the above code which is coded in appcontroller

like:
Call to a member function check() on a non-object

it will generate due to Empty session variable

Upvotes: 0

MUY Belgium
MUY Belgium

Reputation: 2452

Use the session helper (required for authentication as showed in the "log tutorial") :

if ($this->Session->read('Auth.User')) {
    echo 'logged';
} else {
    echo 'guest';
}

Upvotes: 4

JJJ
JJJ

Reputation: 33163

Follow the MVC pattern and put the logic in the controller.

In the controller:

$this->set( 'loggedIn', $this->Auth->loggedIn() );

In the view:

if( $loggedIn ) { 
    echo $this->element( 'user' );
}
else {
    echo $this->element( 'guest' );
} 

Upvotes: 15

Oldskool
Oldskool

Reputation: 34837

Try this:

$element = (AuthComponent::loggedIn()) ? 'user' : 'guest';
echo $this->element($element);

Pretty similar to what you already tried, but then calling the loggedIn method statically.

Upvotes: 2

Related Questions