Preston Garvey
Preston Garvey

Reputation: 1421

How to delete array of files?

I have a problem with deleting array of files that belonged to a post. I have this update function below :

public function update(Post $post, PostsReq $request) {
        $input = $request->all();
        if ($request->hasFile('image')) {
            $this->deleteImage($post);

            foreach ($request->file('image') as $file) {
                $ext = $file->getClientOriginalExtension();
                $name = $file->getClientOriginalName();

                $image_name = $name . ".$ext";
                $upload_path = 'image';
                $file->move($upload_path, $image_name);
                Photos::create([
                    'post_id' => $post->id,
                    'image' => $image_name,
                ]);
            }
        }
        $post->update($input);
        return redirect()->route('postindex');
    }

What I want is that when the update form receiving new files from the input, it will erase the old files and then replace them with the new ones. But I couldn't make the method to delete the files working. Below is the delete files method :

private function deleteImage(Post $post)   
        $photos = Photos::where('post_id', $post->id)->get();
        $exist = Storage::disk('image')->exists($photos);
        if (isset($photos) && $exist) {
            $delete = Storage::disk('image')->delete($photos);
            if ($delete) {
                return true;
            }
            return false;
        }
    }

Also I'd like to know if there are better approach on doing this, like inserting photos to a post. Like do I have to create a file manager to handle the files and then simply assign the files from there to a post whenever needed ? That's all, thanks!

Upvotes: 1

Views: 346

Answers (2)

Nadjib Khelifati
Nadjib Khelifati

Reputation: 559

You can get array of all path photos by using ->pluck(PATH_PHOTO_COLUMN), and pass a result array to \File::delete for delete all files in same time.

private function deleteImage(Post $post)
{
    $photos = Photos::where('post_id', $post->id)->pluck('photo_path');

    if(count($photos))
    {
        \File::delete($photos);
        return true;
    }

    return false;

}

Upvotes: 2

Sagar Gautam
Sagar Gautam

Reputation: 9389

In your deleteImage function, you need to pluck filename. That is image column in Photos model.

You have to change function like this:

private function deleteImage(Post $post){

    // pluck filename i.e. image from Photos model.

    $photos = Photos::where('post_id', $post->id)->pluck('image');

    $exist = Storage::disk('image')->exists($photos);
    if (isset($photos) && $exist) {
        $delete = Storage::disk('image')->delete($photos);
        if ($delete) {
            return true;
        }
        return false;
    }
}

Hope, This might help you.

Upvotes: 0

Related Questions