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

jasmel's avatar

Deleting parent row when child row deletes

Lets assume i have 3 tables. Students,College and CollegeStudents. Students table consist of all students (all college students) data.College table consist of all college data. And CollegeStudents table consist of a mapping of Students and College. Iam not using soft delete.When i delete college, i can easily remove CollegeStudents data by using relationship since CollegeStudents is a child of College.(onDelete('cascade')). But my problem is ,i want to remove the students from Students table as well when deleting the College row.How come it is possible.is there any way in eloquent to manage this kind of criteria? Advance thanks for your help.

0 likes
4 replies
lostdreamer_nl's avatar

I would suggest using Eloquent's Events for this. You could start by setting it up in the College model:

Class College extends Model {

    public static function boot() 
    {
        parent::boot();
        self::deleting(function(College $college) {
            // This will fire right before actually deleting the college.
            // remove all students from this college
            $college->students()->detach();
            // I think we might only want to delete students that do not belong to any college anymore right?
            Student::doesntHave('colleges')->delete();
            // make sure the delete() command is allowed
            return true;
        });
    }
}

I'm making a few assumptions here:

  1. Colleges <--> Students is a belongsToMany relationship, so students can belong to multiple colleges
  2. You delete the students from the college to be deleted, and afterwords only want to delete the colleges that no longer belong to any college (you dont want to delete a student that belongs to 2 colleges by removing one of those colleges)
  3. The relationship on your college model is called students() and on the student model it's called colleges()

Have fun!

jasmel's avatar

Thanks @lostdreamer_nl .But in my situation i have one more table CollegeStudents.That is the problem.I mapped the College table with collegeStudents table.CollegeStudents also mapped with the Students table.

College->hasMany->CollegeStudents

CollegeStudents->belongsTo->Students

Got my point? i hope you can help me.

biishmar's avatar
$college = College::with('collegeStudent')->where('college_id', $id)->first();

$student_ids = $college->collegeStudent->pluck('student_id');

$college->collegeStudent()->delete();

Student::destroy($student_ids);

$college->delete();
Hitenty's avatar

oh, I have the same issue with my table. it's so hard to fix for me, so I even think to ask for help with my college homework this site. but seems like, I've found the solution here. thank you!

Please or to participate in this conversation.