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');
} '''