phplaravel

Laravel - Delete images from storage / update post


welcome everybody

Post Model

public function images()
{
    return $this->hasMany(PostImages::class);

}

PostImages Model

public function post()
{
    return $this->belongsTo(Post::class);
}

PostsController / update

public function update(UpdatePostRequest $request, Post $post)
{
    //
    $data = $request->only(['title', 'description', 'contents', 'price']);

    if ($request->hasFile('images'))
    {
        $getId = Post::find($post->id);
        $getId->images()->delete();     // --> this delete from database table $post->id

        $uploadPicture = array();
        foreach ($request->file('images') as $photo) {
            $file      = $photo;
            $filename  = $file->getClientOriginalName();
            $picture   = date('His').'-'.$filename;

            $file->move(public_path('storage/images/'), $picture);

            array_push($uploadPicture, new PostImages(array('image' => 'images/'. $picture)));
        }

        $post->images()->saveMany($uploadPicture);
    }

    if ($request->input('contents')) {
        $data['content'] = $request->contents;
    }

    $post->update($data);
}

Database post_images

need delete old images in storage get path databese and update new images


Solution

  • You can use another function to delete the images from the folder. like here,

       private function unlinkPostImages($images)
    {
        if(!empty($images)){
            foreach ($images as $img){
                $old_image = 'YOUR_IMAGE_PATH_HERE/' . $img->image;
                if (file_exists($old_image)) {
                    @unlink($old_image);
                }
            }
        }
    }
    

    Then call this function above image delete function. like this...

    $this->unlinkPostImages($getId->images); // this will delete image from folder
    $getId->images()->delete();     // --> this delete from database table $post->id