It seems like a two-step process to get this,
$u = $this->Auth->user();
$uid = $u['User']['id'];
Isn't there a variable set somewhere once a user is logged in?
It seems like a two-step process to get this,
$u = $this->Auth->user();
$uid = $u['User']['id'];
Isn't there a variable set somewhere once a user is logged in?
You can use $uid = $this->Auth->user('id');
Check the api documentation: https://api.cakephp.org/1.3/class-AuthComponent.html#_user
For everybody using the newer Cakephp v4.x: https://api.cakephp.org/4.4/class-Cake.Controller.Component.AuthComponent.html#user()
In CakePHP there are several ways to get the user id from the session, here are a few examples
To get the session user id within the controller use:
$uid = $this->Auth->User('user_id');
To get the session user id within a view, use: ( Not Recommended, I would set this in the controller)
$uid = $this->Session->read('Auth.User.id');
To get the session user id within a model, use: (Not Recommended, but a solution)
$uid = CakeSession::read('Auth.User.id');
I don't recommend the above to get the session user id from within the model, I would pass it via the controller, use:
$this->Model->function($uid);
You can also get the session user id via pure php, use: (Althought using Cake you should stick with the conventions)
$uid = $_SESSION['Auth']['User']['id'];
And there are more approaches, this is just a few...
You can also get the user details from the session if the Auth class is not available to you.
$this->Session->read('Auth.User.id')
CakePhp 2.x:
Anywhere:
AuthComponent::user('id')
Inside a controller:
$this->Auth->user('id');
Even this question being posted way before present version, I'm gonna answer how to do it in Cakephp v4.x, because I just needed it and got a hard time finding this info, and it may be useful to someone else.
$identity = $this->request->getAttribute('authentication')->getIdentity();
Now, you have an IdentityInterface
ORM-like object, which returns values from pairs named after the DB table you're using to track users. So, you can get all info from your DB, like:
$identity['email']
$identity['full_name']
$identity['id']
// etc
$this->Session
is deprecated, as Simon says above, but now $this->request->session();
is also deprecated.
For now, as August 2021 and CakePhp 4 the correct answer is:
$this->request->getSession()->read('User.id');
This may be of no use, but I was having a error cause by $this->Auth->user();
This problem was solved using this instead. I am not sure of the route of the issue, but it came up when calling a function from a Model in the same action as I used $this->Auth->user();
Using AuthComponent::user('id')
solved the issues.
$this->Session
is deprecated
Use something like this
$session = $this->request->session();
$user_id = $session->read('Auth.User.id');