Custom Web Applications to Grow Your Business

(256) 429-8145

Saving User Activities in cakePHP beforeSave function

There are times when you will like to save user activities to get an idea as to who is doing what. You might not want to use a plugin like luggable. Here is a simple way to do it using the beforeSave function.

public function beforeSave($options = Array()) {
        
        if(isset($this->data['Post']['id'])) {
        
            // get user id
            $user_id = CakeSession::read('Auth.User.id');
            
            // get applicant edited fields
            $activity = '<table class="table table-bordered table-striped"><tr><td>Column</td><td>Value</td></tr>';            
           
            foreach($this->data['Post'] as $key => $value){
                $activity .='<tr><td>'.Inflector::humanize($key).'</td><td>'.$value.'</td></tr>';
            }
            $activity .= '<table>';            
                            
            $this->UserActivity->set([
                'user_id' => $user_id,
                'activity' => $activity,               
                'post_id' => $this->data['Post']['id']
            ]);                        
                
            if($this->UserActivity->save()) {
                
            }
        }        
    }