Home > Blockchain >  delete with eager load in laravel
delete with eager load in laravel

Time:05-06

I'm trying to delete a collection but I want to delete the NFTs related to a collection as well. How do I do this?

‍‍This is my Nft model Nft.php

class Nft extends Model
{
    use HasFactory,SoftDeletes;

    public function collection()
    {
        return $this->belongsTo(Collection::class);
    }
}

This is my collection model Collection.php

class Collection extends Model
{
    use HasFactory, SoftDeletes;
    public function nfts()
    {
        return $this->hasMany(Nft::class);
    }
}

This is my COntroller CollectionController.php

 public function deleteCollection(int $id):RedirectResponse
    {
        Collection::with('nfts')->find($id)->delete();
        return redirect('/collections');
    }

But it did not work!!! pleas help me!!!!!

CodePudding user response:

At user model:

public function collection() {
return $this->belongsTo(Collection::class)->withTrashed(); }

CodePudding user response:

Keep in mind that the observer events are not fired if you use mass delete for example. In the case Collection::with('nfts')->delete(); it might not work.

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class Collection extends Model
{
    /**
     * The "booted" method of the model.
     *
     * @return void
     */
    protected static function booted()
    {
        static::deleting(function ($collection) {
            $collection->nfts()->delete()
        });
    }
}
  • Related