我有一个表,其中包含字段
attachment_id
和file_path
,file_path字段存储来自与附件ID对应的s3存储桶的路径。
当 file_path
字段中的数据更新或删除时,有什么方法可以直接从模型初始化方法或调用事件以从 s3 中删除文件?
只需在该模型内部或外部创建一个方法或助手,从 S3 Bucket 中删除文件,然后设置一个观察者在更新或删除期间触发它
e.i.
在你的模型上
class WhatEver extends Model {
public function deleteS3File( $path ) {
// Delete code here
}
}
然后生成一个Observer
php artisan make:observer WhatEverObserver --model=WhatEver
然后你可以在
updated
和 deleting
事件上调用该方法
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 );
}
}
确保检查Observer 文档
你可以使用
$dispatchesEvents
.
创建一个事件,然后在您的模型中:
class ClassName extends Model
{
protected $dispatchesEvents = [
'updated' => EventName::class
];
}