Search code examples
laravelmodel-view-controllerpivot-tablesql-deletelaravel-query-builder

how to delete data from two pivot table in same time in laravel


i want to delete a project witch containe many 'Devis' and one Devis contain many 'Articals', so when i delete a project,the devis and its articals should deleted too

Here is my code

Project Model :

class Project extends Model{

protected $table = 'project';
protected $primaryKey = 'idp';
protected $fillable = ['pname',];


public function devises()
{
    return $this->belongsToMany(Devis::class);
}}

Devis Model :

class Devis extends Model{

protected $table = 'Devis';
protected $primaryKey = 'idd';
protected $fillable = ['type', 'lot', 'prix_total_avant_tax', 'tax_perse', 'tax_amount', 'prix_total_apre_tax', 'notes',];


public function articals()
{
    return $this->belongsToMany(Artical::class)->withPivot('qte', 'total');
}
}

Artical Model : class Artical extends Model{

protected $table = 'artical';
protected $primaryKey = 'ida';
protected $fillable = [ 'num_art' , 'designation', 'unite','prix_unit',];}

Project table : enter image description here


Devis table : enter image description here


devis_project table 'pivot table' :

enter image description here


artical_devis table 'pivot table' :

enter image description here


Thank You In Advance.


Solution

  • Why don't you try that event of deleting the project make the magic.

    In your Project Model add:

    public static function boot() {
            
            parent::boot();
    
            // This method will be called before deleting $project 
            
            static::deleting(function($project) { 
                 
                $project->devis()->delete();   
            
            });
        }
    

    In your Devis Model add:

    // This method will be called before deleting $devis 
    public static function boot() {
            
            parent::boot();
    
            static::deleting(function($devis) { 
    
                 $devis->articals()->delete();
                 
            });
        }
      
    

    So you can simply

    $project->delete();