posiposi / mikatan-knitting-php

0 stars 0 forks source link

管理画面で画像を更新する際に既存画像を削除する #14

Open posiposi opened 3 months ago

posiposi commented 3 months ago

仕様

参考

  1. AWS SDK for PHPをインストール
    composer require aws/aws-sdk-php
  2. EditItem.phpにS3クライアントを作成
    
    use Aws\S3\S3Client;

protected function afterSave(): void { // S3クライアントの作成 $s3Client = new S3Client([ 'version' => 'latest', 'region' => env('AWS_DEFAULT_REGION'), 'credentials' => [ 'key' => env('AWS_ACCESS_KEY_ID'), 'secret' => env('AWS_SECRET_ACCESS_KEY'), ], ]);

// 既存の画像のURLを取得
$existingImageUrl = $this->eloquentImage::where('item_id', $this->record->item_id)->first()->image;

// 既存の画像のS3キーを取得
$existingImageKey = str_replace('https://' . env('AWS_BUCKET') . '.s3.' . env('AWS_DEFAULT_REGION') . '.amazonaws.com/', '', $existingImageUrl);

// 既存の画像を削除
$s3Client->deleteObject([
    'Bucket' => env('AWS_BUCKET'),
    'Key'    => $existingImageKey,
]);

$this->eloquentImage::where('item_id', $this->record->item_id)->update([
'image' => 'https://' . env('AWS_BUCKET') . '.s3.' . env('AWS_DEFAULT_REGION') . '.amazonaws.com/' . $this->imageOriginalFileName,

]); }