sunnyinho
sunnyinho

Reputation: 53

How to delete image from folder in Laravel for parent and child case

I have created two databases one is parent and another is child. Parent table contains title and description column and child table contains the image column for the parent row. Now I want to delete a row from parent table and delete the image from folder it is stored to.

I have done:-

Code to delete from databases, Code to delete from child table and also remove image from folder the image is saved into, Code to delete rows from parent table.

I could not do:-

Code to delete from folder the image is saved into while deleting parent row.

My controllers are like this[

ProjectControllers controls my parent table ProjectImageControllers controls my child table

//This is my ProjectControllers.php 

public function destroy(Project $project)
    {
        $projectImage = Project::find(request('id'));
        $deleted = $projectImage->delete();
        if($deleted){
            File::delete(public_path('/images/projects/').$projectImage->image);
        }

        $projectList = Project::all();
        return view('admin.project.adminProject', ['success'=> true, 'projectList' => $projectList ]);
    }

]

Also the models relation are as follows[

this is Project.php model


class Project extends Model
{
    public function projectImages(){

        return $this->hasMany(ProjectImages::class);
    }
}


This is ProjectImages.php model


class ProjectImages extends Model
{
    protected $fillable = [
        'image', 'project_id'
    ];
    public function project(){
        return $this->belongsTo(Project::class, 'project_id');
    }
}

]

Upvotes: 1

Views: 1244

Answers (1)

BenHuman
BenHuman

Reputation: 175

Please get the rows of the child table first and then delete the images in the folder one by one as follows:

public function destroy(Project $project)
{
   //first find the Parent object with the help of the id parameter.         
     $project = Project::find(request('id'));

   //find the children list of the parent
     $projectImages = ProjectImages::where('project_id','=',request('id'));

    //delete the images stored in your filesystem one by one 
     foreach($projectImages as $projectImage){

          File::delete(public_path('/images/projects/').$projectImage->image);

     }
    
    //Now,finally delete the parent table data. 
     $project->delete();
    

    $projectList = Project::all();
    
    return view('admin.project.adminProject', ['success'=> true, 'projectList' => $projectList ]);
}

 

Upvotes: 1

Related Questions