Files
autocrm/app/Filament/Tenant/Resources/UserResource/Pages/EditUser.php
T
Vasyka f1afcafa5d fix: duplicate email/phone shows notification instead of crashing
Two-layer protection on MasterResource and UserResource:
1. Form validation via ->rules() with Rule::unique() scoped to company_id
   (prevents DB hit in normal flow, shows inline field error)
2. handleRecordCreation/handleRecordUpdate catches
   UniqueConstraintViolationException as fallback — shows a Filament
   danger notification and halts without showing an error page

Also adds phone uniqueness validation (scoped per tenant).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-09-26 20:16:13 +00:00

55 lines
1.7 KiB
PHP

<?php
namespace App\Filament\Tenant\Resources\UserResource\Pages;
use App\Filament\Tenant\Resources\UserResource;
use Filament\Actions;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
use Filament\Support\Exceptions\Halt;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\UniqueConstraintViolationException;
class EditUser extends EditRecord
{
protected static string $resource = UserResource::class;
protected function getHeaderActions(): array
{
return [Actions\DeleteAction::make()];
}
/** @var array<string> */
protected array $_rolesPicked = [];
protected function handleRecordUpdate(Model $record, array $data): Model
{
try {
return parent::handleRecordUpdate($record, $data);
} catch (UniqueConstraintViolationException $e) {
$msg = str_contains($e->getMessage(), 'email')
? __('Acest email este deja folosit de un alt utilizator.')
: __('Acest număr de telefon este deja folosit de un alt utilizator.');
Notification::make()->danger()->title($msg)->send();
throw new Halt();
}
}
protected function mutateFormDataBeforeSave(array $data): array
{
$this->_rolesPicked = $data['roles_picked'] ?? [];
unset($data['roles_picked']);
return $data;
}
protected function afterSave(): void
{
// Always include the primary role
$picked = $this->_rolesPicked;
if (! in_array($this->record->role, $picked, true)) {
$picked[] = $this->record->role;
}
$this->record->syncRoles(array_unique($picked));
}
}