简体   繁体   中英

Prevent AWS S3 file upload if Laravel transaction fails

I would like to know if there is any way I can prevent a file from uploading to AWS S3 if a transaction in Laravel fails.

For example:

DB::beginTransaction();
try {
foreach ($uploaded as $image) {
    DB::table('images')->insert([
       'product_id' => $product_id,
    ]);
    $path = 'path';
    Storage::disk('s3')->putFileAs('products', $image->url, $path);
    DB::table('images')
         ->where('product_id', 1)
         ->update([
             'product_id' => $product_id,
         ]);
}
    DB::commit();
} catch (Exception $e) {
    DB::rollback();
}

If the first insert is successful, the file will be uploaded to the storage even if the update fails. I need to make sure that the whole transaction commits before uploading. (Ignore the code's logic as it is only for demonstration).

One way of doing it is saving the files in another array and uploading them in another loop once the transaction commits, but I would like to know if there is another way of doing it.

In my opinion you can create a queue job for that after DB::commit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM