Laravel 4,在post方法中删除图像/可能吗?

pat*_*ick 6 php image laravel laravel-4 laravel-routing

我试图删除旧的用户图像,如果用户更新他的个人资料图片.我正在使用Laravel 4.1和资源丰富的UsersController.

更新图片非常适合.一个新的保存在我的文件夹中,文件nave将被覆盖在数据库中.但是,我想删除旧图像.因此,我有以下代码,如果我在路由get'test'的空白页面上使用它,它可以正常工作

$oldimage = Auth::user()->profile_picture;

File::delete('img/profile_pictures/users/' . $oldimage);
Run Code Online (Sandbox Code Playgroud)

每当我尝试将此实现到更新图像的过程中时,旧的不会被删除.我已经记住,我必须在覆盖文件名之前删除旧的.

这是否必须对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.'
    );
}
Run Code Online (Sandbox Code Playgroud)

pat*_*ick 0

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

http://laravel.com/docs/helpers