beforeSave()

Hello everyone, I am trying to modify the data on the EditStudent page before saving it to the database. Upon saving, I have set the redirect to the list page. I am using the beforeSave() method, and as soon as I click the save button in the form, the values change correctly, but then they are not saved to the database. What am I doing wrong? Thank you very much.
2 Replies
NeerGreeN
NeerGreeN6mo ago
<?php namespace App\Filament\Resources\StudentResource\Pages; use App\Filament\Resources\StudentResource; use Filament\Actions; use Filament\Resources\Pages\EditRecord; use function Livewire\before; class EditStudent extends EditRecord { protected static string $resource = StudentResource::class; protected function getHeaderActions(): array { return [ Actions\DeleteAction::make(), ]; } protected function getRedirectUrl(): string { return $this->getResource()::getUrl('index'); } protected function beforeSave(): void { if (isset($this->data['is_private'])) { if ($this->data['is_private']) { $this->data['customer_id'] = null; } } } } I solved it like this: protected function beforeSave(): void { if (isset($this->data['is_private'])) { if ($this->data['is_private']) { $student = Student::find($this->data['id']); $student->customer_id = null; $student->save(); } } }
Tobias Platen
Tobias Platen6mo ago
I think $this->record should return your Model to modify it.
$this->record->customer_id = null;
$this->record->customer_id = null;
Please consider whether this is the right place for your intention. If you edit the model outside of your Filament Resource, this check won't take place. A Laravel Model Observer might be more suitable in this case.