Resize Images after Upload

I have many models that have "image" column. Each image is uploaded using the FileUpload of filament, but I need to resize it to 5 different sizes. I couldn't use Spatie's package as I have "image" field in many models instead of creating one "media" table and creating all images there.

FileUpload::make('image_file_name')
                ->image()
                ->required(),


Right now the solution I am using is writing code in CreateProduct and EditProduct to handle image resize (and deletion of resized images)

Here is an example, which works, but doing this for other 50 models would require duplicating this code 50 times. What else can i do to make sure image resize is handled by a single code base. I could think of probably through an event listener, or a middleware or confuguring FileUpload to do it for all. But I'm unaware how I can achieve this in filament.


protected function beforeSave(): void
    {
        // Runs before the form fields are saved to the database.
        $oldPrimaryImage = $this->record->image_file_name;
        $newPrimaryImage = Arr::first($this->data['image_file_name']);

        // Do this only if new image is received
        if ($oldPrimaryImage !== $newPrimaryImage) {
            ResizeImages::dispatch([$newPrimaryImage]);
            DeleteImages::dispatch([$oldPrimaryImage]);
        }

        // Getting only the values of both arrays to compare
        $oldSecImages = array_values($this->record->sec_images ?: []);
        $newSecImages = array_values($this->data['sec_images'] ?? []);
        $deletedImages = array_diff($oldSecImages, $newSecImages);
        $addedImages = array_diff($newSecImages, $oldSecImages);

        if (count($addedImages)) {
            ResizeImages::dispatch($addedImages);
        }
        if (count($deletedImages)) {
            DeleteImages::dispatch($deletedImages);
        }
    }
Was this page helpful?