Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

armancs's avatar

Delete Eloquent relationship data

I have three table, They are related to each other with the hasMany relationship.Now what i want is that if first table id=1 exist in second table foreign key and third table foreign key then it will delete all related data which have id=1.

my method to delete data:

public function destroy($id) {
    UniversityModel::destroy($id);
    UniversityinfoModel::where('university_id',$id)->delete();
    UniversityAcademicModel::where('university_id',$id)->delete();

}

its work but when I upload it to the server after some hour it deleted all data from my database.

is it okay?

if university id=1 and when in universityinfomodel and universityacadmicmodel have foreignkey id=1 all data will be delete?

0 likes
7 replies
mdeorue's avatar

Question, in the tables structures, you dont set the foreign key?

If you dont create the foreign key, you can use Eloquent observers to trigger some actions on delete University Model. ( https://laravel.com/docs/5.7/eloquent#events )

public function deleting($university)
{
    $university->info()->delete();
    $university->academic()->delete();
}
Leandro_Haruki's avatar

Try using cascading delete in your migrations:

$table->foreign('university_id')->references('id')->on('universities')->onDelete('cascade');
armancs's avatar

@mdeorue don't understand. I also did an eloquent query. its deleted eloquent data correctly but when I upload it live server data getting lost. no, I don't use the foreign key.

where do I need to add deleting method? in my university model? and where I should add $university variable. please let me clear. thanks for your valuable answer.

D9705996's avatar

@armancs - you should create a new observer using php artisan make:observer UniversityObserver --model University

Then in you Univeristy class add

    public function boot()
    {
        University::observe(UniversityObserver::class);
    }

In UniversityObserver delete method add @mdeorue code

1 like
armancs's avatar

where should I use the boot and delete function? in model?

MiguelBarros's avatar

@armancs, yes you can use this on your model (University.php)


protected static function boot()
{
    parent::boot();

    static::deleting(function($model){
        $model->info()->delete();
        $model->academic()->delete();
    });
}

D9705996's avatar

@armancs - you can either add the code I provided to you your University class and create the observer or use @jorpedito's code without using the observer. It's personal preference. I like putting things in observer so I can isolate laravel magic in one place

1 like

Please or to participate in this conversation.