php - 仅在用户上传新图像时更新图像,Laravel

标签 php laravel

我有一个编辑表单,其中有一个图像字段,用户可以根据需要上传新图像。

但如果用户没有上传新照片,我不想验证图像字段,而只使用数据库中已有的照片。并且根本不更新图像字段。

这是我的编辑功能:

public function postEdit($id) {

    $product = Product::find($id);

    // This should be in product model, just testing here
    $edit_rules = array(
        'category_id' => 'required|integer',
        'title' => 'required|min:2',
        'description' => 'required|min:10',
        'price' => 'required|numeric',
        'stock' => 'integer'
    );

    // Add image rule only if user uploaded new image
    if (Input::has('image')) {
        $edit_rules['image'] = 'required|image|mimes:jpeg,jpg,bmp,png,gif';
    }

    $v = Validator::make(Input::all(), $edit_rules);

    if ($product) {

        if ($v->fails()) {
            return Redirect::back()->withErrors($v);
        }

        // Upload the new image
        if (Input::has('image')) {
            // Delete old image
            File::delete('public/'.$product->image);

            // Image edit
            $image = Input::file('image');
            $filename = date('Y-m-d-H:i:s')."-".$image->getClientOriginalName();
            Image::make($image->getRealPath())->resize(600, 600)->save('public/img/products/'.$filename);

            $product->image = 'img/products/'.$filename;
            $product->save();
        }

        // Except image because already called save if image was present, above
        $product->update(Input::except('image'));

        return Redirect::to('admin/products')->with('message', 'Product updated.');
    }

    return Redirect::to('admin/products');
}

使用它我可以更新除图像之外的所有值。

如果我不上传新照片,它会保存所有其他更新的值。

如果我确实上传了一张新照片,它只会忽略它并保存所有其他更新的值,不会上传新照片。

最佳答案

检查请求是否有文件:

public function update(Request $request)
{
  // Update the model.

  if($request->hasFile('photo')) {
    // Process the new image.
  }

  // ...
}

关于php - 仅在用户上传新图像时更新图像,Laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25715178/

相关文章:

php - 如何使用 laravel 5 像电子邮件通知一样发出新邮件通知?

php - Laravel 5.1 Ajax 调用 'Like' 系统没有发生

php - 在 Laravel 中按投票计数对帖子进行排序

php - 使用php和mysql显示相同别名的照片

php - 使用 composer 离线安装 Symfony

php - 如何进行正确的时间计算?

php - 在 Laravel 中创建备份 Controller

javascript - jquery 和 bootstrap 之间的冲突

php - Azure 网站 : Error connecting to Twilio "SSL certificate pro blem: unable to get local issuer certificate (0)"

javascript - ReactJS - 将发布数据传递到服务器