How can I update user records when they log into CakePHP?
If you are using the Cake Auth component, you first need to insert the following line into your beforeFilter function:
$this->Auth->autoRedirect = false;
Setting this value to false will allow the following code to execute after CakePHP's login function has done its magic.
In your login function add:
if ($this->Auth->User()) {
$this->User->id = $this->Auth->user('id');
$this->User->saveField('last_login', date('Y-m-d H:i:s'));
}
Note. Make sure you have the last_login field in your users table and its value is datetime.
source to share
Assuming you are using an embedded application AuthComponent
in your application, you need to set the following property in your controller:
$this->Auth->autoRedirect = false;
This will allow you to use your function login()
(s logout()
) to do something. Information about the user who is currently logged in is available through
$this->Auth->user()
Then you can use this data to accomplish what you want with that user.
As a shameless self-definition, I suggest you take a look at my open source project where I use this technique to create a remember me cookie.
source to share
I believe you can add stuff to the login () function even if autoRedirect is set to true. I was having some problems with implicit redirection (resource limited user request, must log in and then redirected), so I added code to my login function. Everything seems to be fine, and the login autostart function is called additionally.
I would say just go ahead and add your login logic, see if it works for you.
source to share
The pattern I like is to create an afterLogin () hook on the user model. So in your UserController, create something like:
function beforeFilter() {
$this->Auth->autoRedirect = false;
parent::beforeFilter();
}
function login() {
if($this->Auth->User()) {
if(!$this->User->afterLogin($this->Auth->User())) {
return $this->logout();
}
$this->redirect($this->Auth->redirect());
}
}
Then, in the User model, create:
function afterLogin($User) {
// perform actions on $User here
return true; // return false to halt login
}
source to share