[Vuejs]-How to delete multiple photos from the folder when deleting it from database?

1👍

The easiest approach with your current code in mind is to simply loop over the employees and delete as required:

$employees = Employee::whereIn('id', $request->id)->get(); 
foreach($employees AS $employee){
    $currentPhoto = $employee->photo;
    $currentdatePhoto = $employee->afghanidatephoto;

    $employeePhoto = (public_path('img/emp/').$currentPhoto);
    $employeedatePhoto = (public_path('img/date/').$currentdatePhoto);

    if(file_exists($employeedatePhoto)){
        @unlink($employeedatePhoto);
    }

    if(file_exists($employeePhoto)){
        @unlink($employeePhoto);
    }

    $employee->delete();
}

You can wrap the foreach() in a try { ... } catch { ... } block.

The reason your code had issues starts with this line:

$Employee = Employee::whereIn('id', $request->id)->delete(); 

By finalizing that query with ->delete(), you’re deleting the records that match ids. Next, trying to perform operations on $Employee won’t work, as ->delete() doesn’t return an object (I believe it returns a boolean, true), so $Employee->{ ... } is an error.

With all of that in mind, you should be able to query, loop and delete your Employees and their images.

Leave a comment