You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

HandlesDefaultSettingRecordUpdate.php 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace App\Traits;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Support\Facades\Auth;
  5. trait HandlesDefaultSettingRecordUpdate
  6. {
  7. abstract protected function getRelatedEntities(): array;
  8. abstract protected function getFormModel(): string;
  9. protected function handleRecordUpdate(array $data): Model
  10. {
  11. $relatedEntities = $this->getRelatedEntities();
  12. $model = $this->getFormModel();
  13. $existingRecord = $model::where('company_id', Auth::user()->currentCompany->id)
  14. ->latest()
  15. ->first();
  16. foreach ($relatedEntities as $field => $params) {
  17. [$class, $key, $type] = array_pad($params, 3, null);
  18. if ($existingRecord === null || !isset($existingRecord->{$field})) {
  19. continue;
  20. }
  21. if (isset($data[$field]) && $data[$field] !== $existingRecord->{$field}) {
  22. $this->updateEnabledRecord($class, $key, $existingRecord->{$field}, $type, false);
  23. $this->updateEnabledRecord($class, $key, $data[$field], $type, true);
  24. }
  25. }
  26. $defaults = $model::where('company_id', Auth::user()->currentCompany->id)->first();
  27. if ($defaults === null) {
  28. $defaults = $model::create($data);
  29. } else {
  30. $defaults->update($data);
  31. }
  32. return $defaults;
  33. }
  34. protected function updateEnabledRecord($class, $key, $value, $type = null, $enabled = true): void
  35. {
  36. $query = $class::where('company_id', Auth::user()->currentCompany->id)
  37. ->where('enabled', !$enabled);
  38. if ($type !== null) {
  39. $query = $query->where('type', $type);
  40. }
  41. $query->where($key, $value)
  42. ->update(compact('enabled'));
  43. }
  44. }