how to retrieve the current user id in cakephp

3.1k views Asked by At

I am trying to retrieve the id of the current user logged in so i can save it to another table. I've been around stack overflow and found a few ways of doing this but nothing seems to work.

This throws the error: Call to a member function user() on a non-object

$this->Auth->user('id');

This returns a null value:

$this->Session->read('User.id');

I played around with this for a bit https://github.com/mcurry/cakephp_static_user but for some reason it complained that I was calling unregistered functions when I know I had implemented them.

I've tried a few variations of the auth and session lines but they all return null or throw an error. Can anyone shed some light on what I might be missing or doing wrong?

2

There are 2 answers

1
Ben Hitchcock On

Try this:

$loggedInUser = AuthComponent::user();  

This gives the whole user array, if you're just after the id then you need this:

$userId = $loggedInUser['User']['id'];

It's what I'm using where I need it, and it works well for me.

0
XuDing On

It seems like you are not using CakePHP's built-in Auth component. Your code says:

$components = array('DebugKit.Toolbar', 'Session', 'DataTable', 'RequestHandler', 'Usermgmt.UserAuth')

To include CakePHP's Auth component:

$components = array('...', 'Auth')