public function boot() { if (config('cudl.enable')) { $files = \File::files(config('cudl.model_path')); foreach ($files as $path) { include_once $path; } $namespace = config('cudl.model_namespace'); $models = collect(get_declared_classes())->map(function ($className) use($namespace) { return starts_with($className, $namespace) && $className == $namespace . '\\' . class_basename($className) ? $className : null; })->reject(function ($className) { return is_null($className); })->toArray(); foreach ($models as $modelName) { $model = new $modelName(); $model::created(function ($model) { $action = 'create'; $tableName = $model->getTable(); $id = $model->getKey(); $fields = $model->getAttributes(); $createdAt = Carbon::now(); $createdId = \Auth::check() ? \Auth::User()->getKey() : 0; foreach ($fields as $fieldName => $fieldValue) { if (is_array($fieldValue)) { $fieldValue = json_encode($fieldValue); } $cudl = new CudLog(); $cudl->action = $action; $cudl->table_name = $tableName; $cudl->foreign_key = $id; $cudl->field_name = $fieldName; $cudl->field_after = $fieldValue; $cudl->created_at = $createdAt; $cudl->created_id = $createdId; $cudl->save(); } }); $model::updating(function ($model) { if (method_exists($model, 'getDifferences')) { $action = 'update'; $tableName = $model->getTable(); $fields = $model->getDifferences(); $id = $model->getKey(); $createdAt = Carbon::now(); $createdId = \Auth::check() ? \Auth::User()->getKey() : 0; foreach ($fields as $fieldName => $field) { $cudl = new CudLog(); $cudl->action = $action; $cudl->table_name = $tableName; $cudl->foreign_key = $id; $cudl->field_name = $fieldName; $cudl->field_before = is_array($model->getOriginal($fieldName)) ? json_encode($model->getOriginal($fieldName)) : $model->getOriginal($fieldName); $cudl->field_after = is_array($model->getAttribute($fieldName)) ? json_encode($model->getAttribute($fieldName)) : $model->getAttribute($fieldName); $cudl->created_at = $createdAt; $cudl->created_id = $createdId; $cudl->save(); } } }); $model::deleting(function ($model) { $action = 'delete'; $tableName = $model->getTable(); $id = $model->getKey(); $createdAt = Carbon::now(); $createdId = \Auth::check() ? \Auth::User()->getKey() : 0; $cudl = new CudLog(); $cudl->action = $action; $cudl->table_name = $tableName; $cudl->foreign_key = $id; $cudl->created_at = $createdAt; $cudl->created_id = $createdId; $cudl->save(); }); } } }