6

如果用户更新他的个人资料图片,我正在尝试删除旧用户图像。我正在使用 Laravel 4.1 和一个足智多谋的用户控制器。

更新图片效果很好。一个新的保存在我的文件夹中,并且文件 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.'
    );
}
4

2 回答 2

1

为什么不使用刚刚检索到的 User 模型来获取旧图像?

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);
}
于 2014-01-17T09:07:19.983 回答
0

我找到了一种方法,方法是创建一个辅助函数,然后在控制器方法中调用辅助函数。

http://laravel.com/docs/helpers

于 2014-01-17T07:55:40.627 回答