I have the following code:
Auth->user())
{
echo $this->element(\'header\');
}
else
{
e
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.
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');
}
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.
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')) {
}
?>
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()
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