如果用户更新了他的个人资料图片,我正在尝试删除旧用户图片。我正在使用 Laravel 4.1 和足智多谋的 UsersController。
更新图片效果非常好。一个新的保存在我的文件夹中,文件中殿在数据库中被覆盖。但是,我想删除旧图像。因此,我有以下代码,如果我在带有 route get 'test' 的空页面上使用它,它就可以正常工作
$oldimage = Auth::user()->profile_picture;
File::delete('img/profile_pictures/users/' . $oldimage);
每次我尝试将此实现到更新图像的过程中时,旧的都不会被删除。我已经想到在覆盖文件名之前我必须删除旧的。
这与 Controller 用于更新的 POST 方法有什么关系吗?我该如何解决?
public function update($id){
$validation = Validator::make(
Input::all(), [
'name'=>'required',
'surname'=>'required',
'email'=>'required',
'email' => 'email']);
if($validation->fails()){
return Redirect::to(
'dashboard#profile'
)->withInput()->withErrors(
$validation->messages());
}
$user = User::find($id);
$user->name = Input::get('name');
$user->surname = Input::get('surname');
$user->email = Input::get('email');
if (Input::hasFile('profile_picture_update')) {
$oldimage = Auth::user()->profile_picture;
File::delete('img/profile_pictures/users/' . $oldimage);
}
$imageFile = Input::file('profile_picture_update');
$newprofile_picture = Image::make(
$imageFile->getRealPath()
)->resize(400, null, true)->crop(400, 400);
$name = time() . '-' .
Input::get('name') .
'-' . Input::get('surname') .
'.' . $imageFile->getClientOriginalExtension();
// $name = time() . '-' . $profile_picture->getClientOriginalName();
// Below the profile_picture variable is overrridden.
$newprofile_picture = $newprofile_picture->save(
public_path().'/img/profile_pictures/users/'.$name
);
$user->profile_picture = $name;
$user->save();
return Redirect::to(
'dashboard#profile'
)->with(
'updatemessage', 'Yep! Deine Änderungen wurden gespeichert.'
);
}
最佳答案
为什么不使用刚刚检索到的用户模型来获取旧图像?
if (Input::hasFile('profile_picture_update')) {
$oldimage = Auth::user()->profile_picture;
File::delete('img/profile_pictures/users/' . $oldimage);
}
替换为
if (Input::hasFile('profile_picture_update')) {
$oldimage = $user->profile_picture;
File::delete('img/profile_pictures/users/' . $oldimage);
}
关于php - Laravel 4,在发布方法/可能中删除图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21139342/