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.

EditAccount.php 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace App\Filament\Resources\AccountResource\Pages;
  3. use App\Filament\Resources\AccountResource;
  4. use App\Models\Banking\Account;
  5. use Filament\Pages\Actions;
  6. use Filament\Resources\Pages\EditRecord;
  7. use Illuminate\Database\Eloquent\Model;
  8. use Illuminate\Support\Facades\DB;
  9. class EditAccount extends EditRecord
  10. {
  11. protected static string $resource = AccountResource::class;
  12. protected function getActions(): array
  13. {
  14. return [
  15. Actions\DeleteAction::make(),
  16. ];
  17. }
  18. protected function getRedirectUrl(): string
  19. {
  20. return $this->getResource()::getUrl('index');
  21. }
  22. protected function mutateFormDataBeforeSave(array $data): array
  23. {
  24. $data['company_id'] = auth()->user()->currentCompany->id;
  25. return $data;
  26. }
  27. protected function handleRecordUpdate(Model|Account $record, array $data): Model|Account
  28. {
  29. $currentCompanyId = auth()->user()->currentCompany->id;
  30. $accountId = $record->id;
  31. $enabledAccountsCount = Account::where('company_id', $currentCompanyId)
  32. ->where('enabled', true)
  33. ->where('id', '!=', $accountId)
  34. ->count();
  35. if ($data['enabled'] === true && $enabledAccountsCount > 0) {
  36. $this->disableOtherAccounts($currentCompanyId, $accountId);
  37. } elseif ($data['enabled'] === false && $enabledAccountsCount < 1) {
  38. $data['enabled'] = true;
  39. }
  40. return parent::handleRecordUpdate($record, $data);
  41. }
  42. protected function disableOtherAccounts($companyId, $accountId): void
  43. {
  44. DB::table('accounts')
  45. ->where('company_id', $companyId)
  46. ->where('id', '!=', $accountId)
  47. ->update(['enabled' => false]);
  48. }
  49. }