Handling update and adding a field to data in Laravel Filament

1.5k views Asked by At

In Laravel Filament, I want to add created_by field in create operation and updated_by in update operation.

I can succeed while I create, as follows in Pages/CreateModule.php file.

protected function mutateFormDataBeforeCreate(array $data): array
{
    $data['created_by'] = auth()->id();
    return $data;
}

But When I try a method similar function:

protected function mutateFormDataBeforeUpdate(array $data): array
{
    $data['updated_by'] = auth()->id();
    return $data;
}

does nothing.

How can I hook the update operation in Laravel Filament?

3

There are 3 answers

0
tolga On BEST ANSWER

I found a solution. Proper place is Edit page, not create. The proper method is handleRecordUpdate.

In Pages/EditModule.php:

protected function handleRecordUpdate(Model $record, array $data): Model
{
    $data['updated_by'] = auth()->id();
    $record->update($data);

    return $record;
}
0
Virginus Alajekwu On

try this:

use Filament\Resources\MyResource\MyResource;

   class MyCustomController extends MyResource
   {
       public function update($record, $request)
       {
           // Get the existing data before updating
           $data = $record->toArray();

           // Merge the updated_by field
           $data['updated_by'] = auth()->id();

           // Update the record with the modified data
           $record->update($data);

           // You can perform additional actions here if needed.

           // Redirect or respond as necessary.
       }
   }
1
guifarro On

you can use mutateFormDataBeforeSave on Pages/EditModule.php