mgsmus Hocam yapamadım, resimleri diskten silmiyor bir türlü.
Öncelikle model eventlerde deleted yaparsam products tablosundan ilgili satır silinince, images tablosundaki product_id foreign key null olamayacağından hataya düşüyor. O yüzden deleting ile işlem yapıyorum.
Product modelimde;
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected static function booted()
{
static::deleting(function ($product) {
if ($product->images() != null) {
$product->images()->delete();
}
});
}
}
Bu kod çalışıyor. Ürünü silersem, images tablosunda o product_id 'ye ait bütün kayıtlar siliniyor.
Çalıştıramadığım kısım Image modeli;
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
class Image extends Model
{
protected static function booted()
{
static::deleting(function ($image) {
foreach ($image as $key) {
Storage::delete([$key->name]);
}
});
}
}
public diski kullanıyorum. Normalde resim silerken Storage::delete
içerisinde direkt $path vermem yeterli oluyor.
Resimler images tablosunda name sütunu altında products/aZmH5cXzno5M4mGP.jpg şeklinde Laravel store ile otomatik oluşturuluyor.
Şuradaki ilk cevabı da denedim işe yaramadı;
https://stackoverflow.com/questions/41097625/delete-images-that-are-in-elequent-relationship
Örnek sanırım eski File yerine Storage:: ile yaptım. public_path kullanmama gerek olmamalı çünkü .env dosyamda FILESYSTEM_DRIVER=public olarak tanımlı. storage/app/public olarak kendisi ekliyor, name alanında zaten products klasör ismi ve dosya adı da tutuluyor yukarıda yazdığım gibi. Neden olmuyor çözemedim.