如何从Laravel的文件夹中删除父子案例的图像

时间:2020-09-06 07:53:00

标签: laravel eloquent

我创建了两个数据库,一个是父数据库,另一个是子数据库。父表包含标题和描述列,子表包含父行的图像列。现在,我想从父表中删除一行,并从存储在其中的文件夹中删除该图像。

我已经完成:-

要从数据库中删除的代码, 从子表中删除并从保存图像的文件夹中删除图像的代码, 用于从父表中删除行的代码。

我做不到:-

在删除父行时从保存图像的文件夹中删除的代码。

我的控制器就是这样[

ProjectControllers控制我的父表 ProjectImageControllers控制我的子表

//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 ]);
    }

]

模型关系如下[

这是Project.php模型


class Project extends Model
{
    public function projectImages(){

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


这是ProjectImages.php模型


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

]

1 个答案:

答案 0 :(得分:0)

请先获取子表的行,然后按如下所示逐个删除文件夹中的图像:

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 ]);
}