mercredi 19 février 2020

How can i delete the previous image from the storage when an image is changed in laravel?

i am currently trying to delete an image when a user updates his/her post before publishing. everything works fine, the image is changed in the database and post page, but i want to delete the previous image. Here is my controller

public function updatePost(Request $request){
    $data = $request->all();
    $postid = $request['id'];
    $isExist = Post::where('id', $postid)->first();
    if($isExist){
        if ($request->hasFile('image')) {

            $file = $request->File('image');
            //Get filename with extension
            $fileNameToStoreWithExt = $file[0]->getClientOriginalName();
            //Get just filename
            $filename = pathinfo($fileNameToStoreWithExt, PATHINFO_FILENAME);
            //Get just ext
            $extension = $file[0]->getClientOriginalExtension();
            //File to store
            $fileNameToStore = $filename . '_' . time() . '.' . $extension;
            //Upload Image
            $path = $file[0]->storeAs('image', $fileNameToStore);
            $file[0]->move('storage/image', $fileNameToStore);
            File::delete(public_path('storage/image'.$isExist['image']));
            Post::where('id', $postid)->update([
                'title' => $data['title'],
                'category' => $data['category'],
                'content' => $data['content'],
                'image' => $path
            ]);
            return response()->json([
                'status'=>'200',
                'response'=> 'successfully updated'
            ]);
        }else{
            Post::where('id', $postid)->update([
                'title' => $data['title'],
                'category' => $data['category'],
                'content' => $data['content']
            ]);
            return response()->json([
                'status'=>'200',
                'response'=> 'successfully updated'
            ]);
        }
    }else{
        return response()->json([
            'error'=> 'post does not exist'
        ]);
    }
}

i used File::delete(public_path('storage/image'.$isExist['image'])); but it didn't do the job



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2HGyRhM
via IFTTT

Aucun commentaire:

Enregistrer un commentaire