【问题标题】:Only update image if user uploaded a new one, Laravel仅在用户上传新图像 Laravel 时更新图像
【发布时间】:2020-04-07 03:06:50
【问题描述】:

我有一个编辑表单,其中有一个图像字段,用户可以在其中上传新图像,如果他愿意的话。

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

这是我的编辑功能:

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');
}

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

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

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

【问题讨论】:

  • 您是否尝试将$product->update(...); 放在else 子句中?
  • 刚刚试过。它没有工作..
  • 你确定 Laravel 得到了图像吗?您的文件输入名称是否正确?您的表单 ecntype 是否设置为 multipart/form-data
  • 谢谢..它的作品..
  • 你需要这个更新Update post and delete images

标签: php laravel


【解决方案1】:

检查请求是否有文件:

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

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

  // ...
}

【讨论】:

  • @sohaieb,很高兴这有帮助!不要忘记通读 Laravel 文档。这是有史以来写得最好的文档之一!
【解决方案2】:
public function update() {

    $id=Input::get('id');
    $rules= array('name'=>'required|regex:/(^[A-Za-z]+$)+/',
                        'detail'=>'required|regex:/(^[A-Za-z]+$)+/',
                        'images' => 'required|image');
    $dat = Input::all();

    $validation = Validator::make($dat,$rules);
    if ($validation->passes()){

        $file =Input::file('images');
        $destinationPath = 'image/pack';
        $image = value(function() use ($file){
        $filename = date('Y-m-d-H:i:s') . '.' . $file->getClientOriginalExtension();
        return strtolower($filename);
            });

        $newupload =Input::file('images')->move($destinationPath, $image);


        DB::table('pkgdetail')
                        ->where('id', $id)  
                                ->limit(1)  
                            ->update(array('name' => Input::get('name'), 'detail' => Input::get('detail'), 'image' => $newupload));


        $data=PackModel::get_all();
         return View::make('pkg_dis')->with('data',$data)
                                    ->withErrors($validation)
                                ->with('message', 'Successfully updated.');
        }

}

【讨论】:

    【解决方案3】:

    使用 Illuminate\Support\Facades\Input;

    public function update(Request $request, $id)
    {
        if ($tag = Tag::find($id))
        {
            $this->validate($request, [
            'tag_name' => 'required|min:3|max:100|regex: /^[a-zA-Z0-9\s][a-zA-Z0-9\s?]+$/u|unique:tags,tag_name,'.$id.',id',
            ]);
            $tag->tag_name=$request->input('tag_name');
    
            // get the image tag_img_Val
            if($request->hasFile('tag_image'))
            {
                $this->validate($request, [
                'tag_image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:1000',
                ]);
                $img = $request->file('tag_image');
                $old_image = 'uploads/' . $tag->tag_image;//get old image from storage
                if ($img != '')
                {
                    $image = rand() . '_' . ($img->getClientOriginalName());
                    $path = 'uploads/';
                    //Storing image                
                    if ($img->move(public_path($path), $image))
                    {
                        $tag->tag_image = $image;
                        if ($tag->update())
                        {
                            if (is_file($old_image)) {
                                unlink($old_image); // delete the old image 
                            }
                            return response()->json(['message' => 'Tag has been updated successfully.'],200);
                        }
                        else
                        {
                            unlink($image); // delete the uploaded image if not updated in database
                            return response()->json(['message' => "Sorry, Tag not updated"],500);
                        }
                    }
                    else
                    {
                        return response()->json(['message' => "Sorry, Image not moved"],500);
                    }
                }
                else
                {
                    return response()->json(['message' => "Sorry, Image not uploaded"],500);
                }
            }
            else
            {
                if($tag->update(Input::except('tag_image')))
                {
                    return response()->json(['message' => 'Tag has been updated successfully.'],200);
                }
                else
                {
                    return response()->json(['message' => "Sorry, Tag not updated"],500);
                }
            }
        }
        else
        {
            return response()->json(['message' => 'Tag not found'], 404);
        }
    }
    

    【讨论】:

      【解决方案4】:

      您需要使用multipart 进行表单编码

      【讨论】:

        【解决方案5】:

        您可以使用其他功能从文件夹中删除图像。喜欢这里

        private function unlinkPostImages($images)
        {
            if(!empty($images)){
                foreach ($images as $img){
                    $old_image = public_path('storage/' . $img->image);
                    if (file_exists($old_image)) {
                        @unlink($old_image);
                    }
                }
            }
        }
        

        然后在图片删除函数上面调用这个函数。像这样……

        $this->unlinkPostImages($getId->images); // this will delete image from folder
        $getId->images()->delete();     // --> this delete from database table $post->id
        

        same this Click here..

        我的更新功能

        public function update(UpdatePostRequest $request, Post $post)
        {
            //
            $data = $request->only(['title', 'description', 'contents', 'price']);
        
            // صورة الإعلان //
            if ($request->hasFile('image')) {
        
                Storage::disk('public')->delete($post->image);
        
                $imagePath            = $request->image;
                $filename             = Str::random(10).'-'.time().'-'.$imagePath->getClientOriginalName();
                $image_resize         = Image::make($imagePath->getRealPath());
        
                $image_resize->fit(120);
                $image_resize->orientate();
                $image_resize->save(public_path('storage/images/' .$filename), 100);
        
                $sImg                 = 'images/'. $filename;
                $data['image']        = $sImg;
        
            }
            // -------- //
        
            if ($request->hasFile('images'))
            {
                $getId = Post::find($post->id);
                $this->unlinkPostImages($getId->images);
                $getId->images()->delete();
        
                $uploadPicture = array();
                foreach ($request->file('images') as $photo) {
                    $file      = $photo;
                    $filename  = $file->getClientOriginalName();
                    $picture   = date('His').'-'.$filename;
        
                    $file->move(public_path('storage/images/'), $picture);
        
                    array_push($uploadPicture, new PostImages(array('image' => 'images/'. $picture)));
                }
        
                $post->images()->saveMany($uploadPicture);
            }
        
            if ($request->input('contents')) {
                $data['content'] = $request->contents;
            }
        
            //dd($data);
            $post->update($data);
            session()->flash('SUCCESS', 'تم تحديث الإعلان بنجاح.');
            return redirect()->route('post.show', [$post->id, Post::slug($post->title)]);
        }
        

        【讨论】:

          【解决方案6】:

          在控制器部分:

              $destinationPath = 'uploads';
              $extension = Input::file('image')->getClientOriginalExtension();
              var_dump($extension);
              $fileName = rand(11111,99999).'.'.$extension;
              Input::file('image')->move($destinationPath, $fileName);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-11-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多