try using Storage
if ($oldImage && Storage::exists($oldImagePath)) { Storage::delete($oldImagePath); }
I have tried this but this does not working. Laravel 11 is not passing the user variable on editing (breeze).
Just wanna remove the old image when user want new image.
public function update(ProfileUpdateRequest $request): RedirectResponse
{
$user = auth()->user();
$request->user()->fill($request->validated());
if ($request->hasFile('image')) {
// Delete the old image if it exists
$oldImage = $user->image;
$filePath = public_path('images/user_img/' . $oldImage);
if ($oldImage && File::exists($filePath)) {
File::delete($filePath);
echo "File deleted successfully.";
} else {
echo "File does not exist: " . $filePath;
}
// Upload image
if ($request->hasFile('image')) {
$filename = 'image' . '_' .time() . '.' . $request->file('image')->getClientOriginalExtension();
$request->file('image')->storeAs('user_img', $filename, 'public');
$request->user()->image = $filename;
}
}
if ($request->user()->isDirty('email')) {
$request->user()->email_verified_at = null;
}
$request->user()->save();
return Redirect::route('profile.edit')->with('status', 'profile-updated');
}
Please or to participate in this conversation.