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

lukeboy_2002's avatar

Filament: Delete old image at edit

I want to delete te old image if I edit and changed the image in the edit form of filament. Can this be done?

my create and edit code:

public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Card::make()
                    ->schema([
                        TextInput::make('title')
                            ->unique(ignoreRecord: true)
                            ->required(),
                        ColorPicker::make('color_title'),
                        TextInput::make('subtitle')
                            ->required(),
                        ColorPicker::make('color_subtitle'),
                        FileUpload::make('image')
                            ->getUploadedFileNameForStorageUsing(function (TemporaryUploadedFile $file): string {
                                $fileName = $file->hashName();
                                $name = explode('.', $fileName);
                                return (string) str('slides/'.$name[0].'.png');
                            })
                            ->label('Image')
                            ->maxSize(3072)
                            ->image()
                            ->required(),
                        Toggle::make('active'),
                    ])
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('id')->sortable(),
                ImageColumn::make('image'),
                TextColumn::make('title')->sortable()->searchable(),
                TextColumn::make('subtitle')->sortable()->searchable(),
                BooleanColumn::make('active')->sortable(),
            ])
            ->filters([
                //
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\DeleteBulkAction::make(),
            ]);
    }
0 likes
4 replies
bappondakash's avatar

Edit and delete image.

premiumbd04@gmail.com I want to delete te old image if I edit and changed the image in the edit form of filament. Can this be done?

my create and edit code:

public static function form(Form $form): Form { return $form ->schema([ Card::make() ->schema([ TextInput::make('title') ->unique(ignoreRecord: true) ->required(), ColorPicker::make('color_title'), TextInput::make('subtitle') ->required(), ColorPicker::make('color_subtitle'), FileUpload::make('image') ->getUploadedFileNameForStorageUsing(function (TemporaryUploadedFile $file): string { $fileName = $file->hashName(); $name = explode('.', $fileName); return (string) str('slides/'.$name[0].'.png'); }) ->label('Image') ->maxSize(3072) ->image() ->required(), Toggle::make('active'), ]) ]); }

public static function table(Table $table): Table
{
    return $table
        ->columns([
            TextColumn::make('id')->sortable(),
            ImageColumn::make('image'),
            TextColumn::make('title')->sortable()->searchable(),
            TextColumn::make('subtitle')->sortable()->searchable(),
            BooleanColumn::make('active')->sortable(),
        ])
        ->filters([
            //
        ])
        ->actions([
            Tables\Actions\EditAction::make(),
            Tables\Actions\DeleteAction::make(),
        ])
        ->bulkActions([
            Tables\Actions\DeleteBulkAction::make(),
        ]);
}

Yes, it is possible to delete the old image when a new one is uploaded through the edit form of the filament. You can achieve this by implementing the following steps:

First, you need to check if a new image has been uploaded or not. You can do this by checking if the image field in the form data is empty or not.

If a new image has been uploaded, you can delete the old image from the storage using the Storage::delete() method. You can get the path of the old image from the database by fetching the record with the given ID and then accessing the image field.

After deleting the old image, you can save the new image to the storage and update the record in the database with the new image path.

Here's an example implementation of the update method in your controller: ''' public function update(Request $request, $id) { $record = Record::findOrFail($id);

$form = MyForm::form()->forRecord($record);

$data = $form->handleRequest($request)->getData();

// Check if a new image has been uploaded
if (!empty($data['image'])) {
    // Delete the old image
    Storage::delete($record->image);

    // Save the new image to the storage
    $imagePath = $data['image']->store('slides', 'public');

    // Update the record with the new image path
    $record->update(['image' => $imagePath]);
}

$record->update($data);

return redirect()->route('my-route');

} '''

lukeboy_2002's avatar

@bappondakash I don't have a controller, must I have one? Is it possible to rename the file to the ID so it overrides the old one.

_GR_'s avatar

There are several ways to add listeners, one of them into directly your model you can do like so:

    protected static function boot()
    {
        parent::boot();

        /** @var Model $model */
        static::updating(function ($model) {
            if ($model->isDirty('image') && ($model->getOriginal('image') !== null)) {
                Storage::disk('public')->delete($model->getOriginal('image'));
            }
        });
    }

in this case, while saving the model, listener will checks if image path has been changed and previous value exists, then old image file deletion will be triggered.

8 likes
dabliuweb's avatar

Just overrides the mutateFormDataBeforeSave() method in resource editRecord class (app/Filament/Resources/ClientsResource/Pages/EditClients.php)

use Illuminate\Support\Facades\Storage;

public function mutateFormDataBeforeSave(array $data): array
    {
        if($this->record->isDirty("image") || $this->record->image === null) return $data;
        Storage::disk(getenv('FILAMENT_FILESYSTEM_DISK'))->delete($this->record->image);
        return $data;
    }

Please or to participate in this conversation.