laravel 当表中的记录更新时自动删除文件

a7qyws3x  于 2023-03-04  发布在  其他
关注(0)|答案(2)|浏览(93)

我有一个表,其中包含字段attachment_idfile_path,file_path字段存储了与附件id对应的s3桶的路径。当file_path字段中的数据更新或删除时,是否有任何方法可以初始化方法或直接从模型调用事件以从s3删除文件?

8e2ybdfx

8e2ybdfx1#

只需在模型内部或外部创建一个方法或帮助器,从S3Bucket中删除文件,然后设置一个观察器在更新或删除过程中触发它

在你的模型上

class WhatEver extends Model  {

    public function deleteS3File( $path ) {
        // Delete code here 
    }
}

然后生成观察者

php artisan make:observer WhatEverObserver --model=WhatEver

则可以在updateddeleting事件上调用该方法

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

请务必查看观察员文档

osh3o9ms

osh3o9ms2#

您可以使用**$调度事件**
创建一个事件,然后在模型中,

class ClassName extends Model
{
    protected $dispatchesEvents = [
        'updated' => EventName::class
    ];
}

看看这个:https://laravel.com/docs/9.x/eloquent#events

相关问题