LoginSignup
0

posted at

updated at

Laravelでstorage配下の画像削除

環境

  • Laravel5.8
  • PHP7.4

何をするか?

LaravelによるWEBサービスで画像登録などを行うことも多いと思います。

  • ユーザーのプロフィール画像
  • 投稿コンテンツのサムネイル画像
  • 商品画像etc...

そしてそれらはWEBサービス上で削除される可能性もあります。
ユーザーが退会したり、商品画像の変更や削除ですね。
その際にプロジェクト内の実際の画像も削除しないとプロジェクト内がユーザーやコンテンツが増えるたびに肥大化します。

それを防ぐために実際の画像も削除していきましょう。

コントローラー内はシンプルにアイテムを一つ取得してそれの画像を消す処理です。

php artisan storage:link

既に上記コードででシンボリックを貼ってる前提です。

Controller.php
  namespace App\Http\Controllers;
  use App\Item;
  use Illuminate\Support\Facades\Storage;

    public function item_delete($id)
    {

        $item = Item::find($id);
        Storage::disk('public')->delete('images/' . $item->image);
                

        return view('project.mypage');

    }

Storageクラス

こちらでStorageクラスを使用します。

Controllere.php
use Illuminate\Support\Facades\Storage;

下記で/storage/app/public/にアクセスできます。

Controllere.php
 Storage::disk('public');

削除する場合はdeleteを付けて引数にさらにパスを指定。
下記は/storage/app/public/images/画像ファイル名 を削除しています。

Controllere.php
Storage::disk('public')->delete('images/'.$item->image)

以上です。
その他にもput、get、putfileなど色々とあります。

参考

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
0