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('');
}
CodePudding user response:
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...