0

In laravel 8 app I with spatie/laravel-medialibrary 9 I want to delete file from storage when I delete parent model with boot method, like

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Validation\Rule;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;

class Photo extends Model  implements HasMedia
{
    use HasFactory;
    use InteractsWithMedia;

    protected $table = 'photos';


    protected static function boot()
    {
        parent::boot();
        static::deleting(function ($photo) {
            \Log::info( ' -1 INSIDEstatic::deleting(::' );
            foreach ($photo->getMedia('photo') as $mediaImage) {
                \Log::info(  varDump($mediaImage->getPath(), ' -1 $mediaImage->getPath()::') );
                if (File::exists($mediaImage->getPath())) {
                    \Log::info(  varDump($mediaImage->getPath(), ' -1 $mediaImage->getPath()::') );
                    Storage::delete($mediaImage);
                }
            }
        });
    }

But file is not deleted and checking logs I see message

 -1 INSIDEstatic::deleting(:

, but not messages inside of

foreach ($photo->getMedia('photo') as $mediaImage) {

loop. Why so ? I expected

static::deleting(function 

is triggered BEFORE rmodel is delete in contoller method :

try {
    DB::beginTransaction();
    $photo->delete();

    DB::commit();

How to make delete these files ?

Thanks!

mstdmstd
  • 2,195
  • 17
  • 63
  • 140
  • 1
    Are you getting an error in your catch block? Does Try logging $photo->getMedia('photos') to see if it returns what you expect it to. – IGP Feb 17 '22 at 16:10
  • 1
    just for testing purposes if you use unlink does it work? – bhucho Feb 17 '22 at 16:29
  • After some additive checks I found that laravel-medialibrary removed files from storage automatically – mstdmstd Feb 22 '22 at 12:02

0 Answers0