skip to Main Content

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?

2

Answers


  1. Chosen as 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;
    }
    

  2. try this:

    use FilamentResourcesMyResourceMyResource;
    
       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.
           }
       }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search