ユーザーがプロフィール写真を更新した場合、古いユーザー画像を削除しようとしています。私は Laravel 4.1 と機知に富んだ UsersController を使用しています。
画像の更新は完全に正常に機能します。新しいものが自分のフォルダーに保存され、ファイル nave がデータベースに上書きされます。ただし、古い画像は削除したいと思います。したがって、次のコードがあります。たとえば、空のページで route get 'test' を使用すると正常に動作します。
$oldimage = Auth::user()->profile_picture;
File::delete('img/profile_pictures/users/' . $oldimage);
これをイメージの更新プロセスに実装しようとするたびに、古いイメージは削除されません。ファイル名を上書きする前に、古いものを削除する必要があることをすでに心に留めています。
これは、コントローラーが更新に使用する 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.'
);
}