crazywolrd23's avatar

when the user upload new image i want to delete the previous image in folder

when the user upload new image i want to delete the previous image in folder

0 likes
4 replies
Sergiu17's avatar

Easy staff

public function update(Request $request, $id) {
    
    $user = User::findOrFail($id);

    if ($request->has('image') {
        if(file_exists('/images/' . $user->image) {
            unlink('/images/' . $user->image);
        }

        $request->image->move('/images', $request->image->getClientOriginalName());

        $user->image = $request->image->getClientOriginalName();
    }

    $user->save();
}

Basic example

1 like
Tray2's avatar

Not knowing what you tried or how you name your images that is uploaded but I would do something like this.

Upload the image and give it the name of the usee id 1.jpgthen when the user uploads another unlink the old one or overwrite it by giving it the same name 1.jpg.

Show us what you tried and we may be able to help you in the right direction.

1 like
crazywolrd23's avatar

#ProfileController class ProfileController extends Controller { public function index($slug){

    return view('profile.index')->with('data', Auth::user()->profile);
}


public function uploadPhoto(Request $request) {
    $this->validate($request, [
      'pic' =>  'mimes:jpeg,png,jpg,gif,svg|required|max:1999'
        ]);

$file = $request->file('pic'); $filename = $file->getClientOriginalName(); $path = 'storage/img';

$file->move($path, $filename); $user_id = Auth::user()->id;

DB::table('users')->where('id',$user_id)->update(['pic' =>$filename]);

return redirect('/editProfile')->withSuccess('Your image was successful.');

}

bhupen's avatar

what my suggestion for you is make to function if(array_exist('image', $input)) $image = uploadimage($input) where you will save the image $this->deleteimage($input) $model = $input['imgae]; return $this->delete(path to the folder and concatenate $at the end will work )

Please or to participate in this conversation.