Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unlinking Image from folder in many to many reationship

I have two models with many to many to many relationships Guardian and Student model. Once guardian is deleted am able to delete student too the problem now is how do i unlink the student Image from my folder once deleted

 case "delete":
            if ($request->method() == "POST") {
                $get_guardian = Guardian::find($id);
                if ($get_guardian) {

                    $delete_guardian = $get_guardian->students();
                    $delete_guardian->unlink("uploads/" . $get_guardian->students()->file);
                    $delete_guardian->delete();
                }

                $get_guardian->delete();
                return redirect('');
            }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

When working with the has-many or many-to-many relationships, if you need to perform specific actions that are not related to the database like unlinking image, you have to loop theough the relation in order to get the specific records. In your case for example:

$get_guardian = Guardian::find($id);

if ($get_guardian) {
    
    foreach($get_guardian->students as $delete_guardian){
        unlink("uploads/" . $delete_guardian->file);
        $delete_guardian->delete();
    }
    
    $get_guardian->delete();    
}

Besides, if you have defined a cascade on delete in your relationship at database level, you won’t need to delete the relationship at all, because the database will automatically delete them when the parent is deleted.

Also, please remember that there are differences between $get_guardian->students and $get_guardian->students(), because the first one returns the result of the relationship, while the second one returns the relationship object. You only need to work with relationship object when you have to use specific eloquent methods like where, etc…

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading