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.

HandlesResourceRecordCreation.php 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace App\Traits;
  3. use App\Models\User;
  4. use Filament\Support\Exceptions\Halt;
  5. use Illuminate\Auth\Access\AuthorizationException;
  6. use Illuminate\Database\Eloquent\Model;
  7. use Illuminate\Support\Facades\DB;
  8. use Illuminate\Validation\ValidationException;
  9. use Throwable;
  10. trait HandlesResourceRecordCreation
  11. {
  12. /**
  13. * @throws Halt
  14. */
  15. protected function handleRecordCreationWithUniqueField(array $data, Model $model, User $user, string|null $uniqueField = null, ?string $uniqueFieldValue = null): Model
  16. {
  17. try {
  18. return DB::transaction(function () use ($data, $user, $model, $uniqueField, $uniqueFieldValue) {
  19. $enabled = (bool)($data['enabled'] ?? false);
  20. if ($enabled === true) {
  21. $this->disableExistingRecord($user->currentCompany->id, $model, $uniqueField, $uniqueFieldValue);
  22. } else {
  23. $this->ensureAtLeastOneEnabled($user->currentCompany->id, $model, $enabled, $uniqueField, $uniqueFieldValue);
  24. }
  25. $data['enabled'] = $enabled;
  26. return $model::create($data);
  27. });
  28. } catch (ValidationException) {
  29. throw new Halt('Invalid data provided. Please check the form and try again.');
  30. } catch (AuthorizationException) {
  31. throw new Halt('You are not authorized to perform this action.');
  32. } catch (Throwable) {
  33. throw new Halt('An unexpected error occurred. Please try again.');
  34. }
  35. }
  36. protected function disableExistingRecord(int $companyId, Model $model, string|null $uniqueField = null, string|null $uniqueFieldValue = null): void
  37. {
  38. $query = $model::query()->where('company_id', $companyId)
  39. ->where('enabled', true);
  40. if($uniqueField && $uniqueFieldValue){
  41. $query->where($uniqueField, $uniqueFieldValue);
  42. }
  43. $existingEnabledRecord = $query->first();
  44. if ($existingEnabledRecord !== null) {
  45. $existingEnabledRecord->enabled = false;
  46. $existingEnabledRecord->save();
  47. }
  48. }
  49. protected function ensureAtLeastOneEnabled(int $companyId, Model $model, bool &$enabled, string|null $uniqueField = null, string|null $uniqueFieldValue = null): void
  50. {
  51. $query = $model::query()->where('company_id', $companyId)
  52. ->where('enabled', true);
  53. if($uniqueField && $uniqueFieldValue){
  54. $query->where($uniqueField, $uniqueFieldValue);
  55. }
  56. $otherEnabledRecord = $query->first();
  57. if ($otherEnabledRecord === null) {
  58. $enabled = true;
  59. }
  60. }
  61. }