logo

CakePHP Automatic created_by and modified_by

cake created_by

As CakePHP has created and modified datetime fields which automatically saved during insert and update operation, after few months development I felt there should also be automatic created_by and modified_by field handling so that we can reduce filling in each time current logged in user’s id in created_by and modified_by field manually.

First of all I looked if CakePHP already has this feature but it was not there, then I wrote my own function with time I Improved it, may be it still need more improvements and can be optimized more, The aim of sharing this with you is, if you are not having such function take it as a handy piece of code, If you already have one, compare it with this function and let me know how can I improve this.

As we need this functionality for all tables so I wrote the code in AppModel, which will execute for each Model.

These are 2 functions

  1. getCurrentUser()
  2. beforeSave()

getCurrentUser()

This is custom function where I am getting current logged-in user’s id

beforeSave()

This is cakePHP’s default callback function which executes before each insert and update operation.

Explaination

  1. First I called parent’s beforeSave() function to do all default things
  2. Got all fields from table in array named $fields
  3. Got current modal name
  4. checked if action is insert(by ifisset if field) and table has created_by field then fill it field with current logged-in user’s id using getCurrentUser function
  5. else if obviously action will be edit, just checked if table has modified_by field then fill it field with current logged-in user’s id using getCurrentUser function

This function will populate created_by and modified_by values in model data before saving, and thus we will have these values in database.

here is the code copy and paste it in your appModel

Comments

    Write a Reply or Comment

    Your email address will not be published. Required fields are marked *