We build custom web applications
to grow your business.

Saving users activity in cakePHP controller

Apart from saving user activities in cakePHP beforeSave, you can also save activities in the controller of which you would like to monitor any change in data. Here is a simple code to do just that. But first, create a mysql table 'user_activities'.

CREATE TABLE `user_activities` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `object_id` int(11) NOT NULL,
  `type` varchar(30) NOT NULL,
  `old_data` text,
  `new_data` text,
  `comment` mediumtext,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=181 DEFAULT CHARSET=latin1;
// get old data first
$old = $this->Post->find('first', [
 'conditions' => [
   'Post.' . $this->Post->primaryKey => $id
   ]
 ;]);
$old = $old['Post'];
// place this after post data
// if ($this->request->is(array('post', 'put'))) {
      // }
           // Get new / edited data from  
            $new = $this->request->data['Post'];
            
            // remove unused variables from old
            $oldMinusNew = array_diff_key($old, $new);            
            foreach ($oldMinusNew as $omn => $value) {
                unset($old[$omn]);
            }
            
            // remove unused variables from old
            $newMinusOld = array_diff_key($new, $old);            
            foreach ($newMinusOld as $nmo => $value) {
                unset($new[$nmo]);
            }            
            
            // unset variables where both old and new match
            foreach ($new as $field => $value) {
                if ($old[$field] == $value) {
                    unset($old[$field]);
                    unset($new[$field]);
                }
            }
            
            $old_data = '';
            foreach($old as $key => $ovalue) {
                $old_data .= $key.': '.$ovalue.'; ';
            }
            
            $new_data = '';
            foreach($new as $key => $nvalue) {
                $new_data .= $key.': '.$nvalue.'; ';
            }
            
            // store user activity
            $this->loadModel('UserActivity');
            $this->UserActivity->create();
            $this->UserActivity->save([
                'UserActivity' => [
                    'user_id' => $this->Auth->user('id'),
                    'object_id' => $this->request->data[' Post ']['id'],
                    'old_data' => $old_data,
                    'new_data' => $new_data,
                    'type' => ' Post Edit',
                    'comment' => $this->request->data[' Post ']['comment']
                ]
            ]);