Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

juanborras's avatar

Filament FileUpload access cancel action

Hey there!

I have a form with an uploadfield. I have developed a custom rule to check the uploaded file. How can I execute some rollback code if the verification fails?

Thanks!

0 likes
2 replies
LaryAI's avatar
Level 58

To handle a rollback when a file upload verification fails in a Filament form, you can utilize Laravel's validation and Filament's form handling capabilities. Here's a step-by-step solution:

  1. Define the FileUpload Field: Use the FileUpload field in your Filament form and specify the validation rules.

  2. Custom Validation Rule: Create a custom validation rule to check the uploaded file. You can do this by creating a new rule class using the Artisan command:

    php artisan make:rule CustomFileValidation
    

    Implement the passes method in your rule class to define the logic for your custom validation.

    <?php
    
    namespace App\Rules;
    
    use Illuminate\Contracts\Validation\Rule;
    
    class CustomFileValidation implements Rule
    {
        public function passes($attribute, $value)
        {
            // Implement your custom validation logic here
            // Return true if validation passes, false otherwise
            return true; // or false based on your logic
        }
    
        public function message()
        {
            return 'The uploaded file did not pass the custom validation.';
        }
    }
    
  3. Apply the Custom Rule in the Form: In your Filament form, apply the custom validation rule to the FileUpload field.

    use App\Rules\CustomFileValidation;
    use Filament\Forms\Components\FileUpload;
    
    FileUpload::make('file')
        ->label('Upload File')
        ->rules(['required', new CustomFileValidation()])
    
  4. Handle Rollback Logic: If the validation fails, Laravel will automatically handle the rollback of the transaction if you are using database transactions. However, if you need to perform additional rollback actions (like deleting a temporary file), you can handle this in the failedValidation method of a custom request or in the catch block of a try-catch statement around your form processing logic.

    Here's an example of handling additional rollback logic:

    try {
        // Your form processing logic here
    } catch (\Illuminate\Validation\ValidationException $e) {
        // Perform rollback actions here, like deleting temporary files
        // Example: Storage::delete($temporaryFilePath);
    
        // Re-throw the exception to ensure the validation error is reported
        throw $e;
    }
    

By following these steps, you can ensure that your custom validation logic is applied to the file upload, and any necessary rollback actions are performed if the validation fails.

1 like

Please or to participate in this conversation.