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

Time:06-19

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.

CodePudding user response:

You can try this: To remove a one-to-many relationship record, use the detach method. The detach method will delete the appropriate record out of the intermediate table, it all depends how you made you migration and what relation type behavior you described there:

/**
 * Remove the specified resource from storage.
 *
 * @param  \App\Models\Project  $project
 * @return \Illuminate\Http\Response
 */
public function destroy(Product $product)
{
    $project->devises()->detach();
    $project->devises()->delete();
    $project->delete();
    
    return redirect()
        ->route('project.index')
        ->withSuccess('Project deleted.');

}

CodePudding user response:

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();

  • Related