i have a table which has the fields attachment_id
and file_path
,file_path field stores the path from s3 bucket corresponding to the attachment id .
is there any way to initialize a method or call an event directly from the model to delete file from s3 when the data in file_path
field is updated or deleted ?
Just create a method or helper inside or outside of that model which delete the file from S3 Bucket, then setup an observer to trigger it during updated or deleting
e.i.
On your model
class WhatEver extends Model {
public function deleteS3File( $path ) {
// Delete code here
}
}
Then generate an Observer
php artisan make:observer WhatEverObserver --model=WhatEver
then you can call that method on updated
and deleting
event
class WhatEverObserver {
// Runs when model is updated
public function updated(WhatEver $whatEvah) {
// Only trigger is file_path column is changed
if ( $whatEvah->isDirty('file_path') ) {
//Get the previous file_path record
$oldPath = $whatEvah->getOriginal('file_path');
//delete the previous file_path
$whatEvah->deleteS3File( $oldPath );
}
}
// Delete the file_path during model deletion
public function deleting( WhatEver $whatEvah ) {
$whatEvah->deleteS3File( $whatEvah->file_path );
}
}
Make sure to check out Observer docs