protected static function boot()
{
parent::boot();
self::creating(function ($model) {
$model->unique_id = self::generateUniqueId();
});
self::deleting(function (Submission $submission) {
Log::info('Deleting model:', ['model' => $submission]);
dd($submission);
// Delete all associated media
$submission->clearMediaCollection('files');
$submission->clearMediaCollection('images');
});
}
我在我的提交模型中有这个方法,创建时可以在每个新模型上工作,但删除不起作用,它只是删除模型,这不起作用
我的提交模型
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\File;
class Submission extends Model implements HasMedia
{
use InteractsWithMedia, HasFactory;
protected $fillable = [
'unique_id',
'user_id',
'title',
'description',
'status',
];
protected static function boot()
{
parent::boot();
self::creating(function ($model) {
$model->unique_id = self::generateUniqueId();
});
self::deleting(function (Submission $submission) {
Log::info('Deleting model:', ['model' => $submission]);
dd($submission);
// Delete all associated media
$submission->clearMediaCollection('files');
$submission->clearMediaCollection('images');
});
}
public static function generateUniqueId()
{
do {
$uniqueId = str_pad(rand(0, 99999999), 12, '0', STR_PAD_LEFT);
} while (self::where('unique_id', $uniqueId)->exists());
return $uniqueId;
}
public function user()
{
return $this->belongsTo(User::class);
}
public function replies()
{
return $this->hasMany(SubmissionReply::class);
}
public function registerMediaCollections(): void
{
$this->addMediaCollection('files')
->useDisk('submissions')
->acceptsFile(function (File $file) {
return in_array($file->mimeType, [
'image/jpeg',
'image/png',
'application/pdf',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'text/plain'
]);
});
$this->addMediaCollection('images')
->useDisk('submissions')
->singleFile()
->acceptsMimeTypes([
'image/jpeg',
'image/png',
'image/jpg',
]);
}
}
该问题可能是由于使用了
dd($submission)
导致的,它会停止执行并阻止媒体被删除。要解决此问题,请删除 dd()
并添加适当的日志记录,以确保触发删除事件并清除媒体。
如果您使用
forceDelete()
,则不会触发 deleting
事件。在这种情况下,请改为监听 forceDeleted
事件
self::forceDeleted(function (Submission $submission) {
$submission->clearMediaCollection('files');
$submission->clearMediaCollection('images');
});