(08-19-2020, 04:22 AM)InsiteFX Wrote: If you take a look at the Model Insert method you can see how CodeIgniter is doing this.
Take a look ad the if statements.
InsiteFX, I followed your advice. Based on what I learned from looking at the CodeIgniter Model, I was able to come up with this:
PHP Code:
/**
* This method saves the session "user_id" value to "created_by" and "updated_by" array
* elements before the row is inserted into the database.
*
*/
protected function insertUserstamp(array $data) {
$user_id = session()->get('user_id');
if (!empty($user_id) &&
!array_key_exists('created_by', $data) && !array_key_exists('updated_by', $data)) {
$data['data']['created_by'] = $user_id;
$data['data']['updated_by'] = $user_id;
}
return $data;
}
/**
* This method saves the session "user_id" value to "updated_by" array element before
* the row is inserted into the database.
*
*/
protected function updateUserstamp(array $data) {
$user_id = session()->get('user_id');
if (!empty($user_id) && !array_key_exists('updated_by', $data)) {
$data['data']['updated_by'] = $user_id;
}
return $data;
}
I then included them in the $beforeInsert and $beforeUpdate arrays. Everything seems to be working correctly.
I do have one followup question. What is the best way to make these methods available to every model in App\Models? Should I create a new "CustomModel" that extends Model with these methods, and make all models located in App\Models children of the new custom model?