I can upload profile image like this
$file_name=$user->id.time().'.'.$request->image->extension();
$request->image->move(public_path('images/profile'),$file_name);
$path="/images/profile/$file_name";
$user->image=$path;
$user->update();
I have two questions: The first one is How to delete the old image after uploading a new one ?
The second one is Is this path the best practice for uploading profile images of users ?
CodePudding user response:
When using the public
or local
driver you can delete the old profile photo like this.
Storage::delete($user->image);
in your case you are using a directory inside the public folder (which is not recommended) and you could delete it as follows
File::delete($filename);
You will have to do this before saving the new image, so that the previous path is not lost, or save it in a variable if you want to do it later.
Regarding where to save your image it is best to save it in the storage folder.
The public
disk included in your application's filesystems
configuration file is intended for files that are going to be publicly accessible. By default, the public disk uses the local
driver and stores its files in storage/app/public
.
So you could save the file like this
$path = $request->file('avatar')->store('avatars');
$path; // avatars/ik2uQS5purtLjV42uXjCHnquGTWmnesAaC9JJdit.jpg
CodePudding user response:
I recommend you used Media Library Link: https://spatie.be/docs/laravel-medialibrary/v10/introduction
public function storeAvatar(AvatarRequest $request): JsonResponse
{
if ($request->hasFile('avatar')) {
$file = $request->file('avatar');
// If has Avatar, delete old avatar
if ($this->user->getFirstMedia('avatar'))
{
$this->user->clearMediaCollection('avatar');
}
// Add Avatar Collection name: avatar
$this->user->addMedia($file)
->toMediaCollection('avatar');
}
return response()->json([
'success' => true,
'avatar' => $this->user->getFirstMediaUrl('avatar')
]);
}