mercredi 4 décembre 2019

Product upload with Dropzone and Laravel

I want to upload a product with multiple images using Dropzone, I have a form which has other fields like price, name etc. I have seen other tutorials but they only upload images not images with other fields(price, name) at once. I have set the Dropzone which shows the preview but if I submit the button I get a validation Please enter product image. How can I pass images to the controller using Dropzone?

Controller

 public function store(Request $request)
 {
  $formInput=$request->except('filename');

    $product = product::create(array_merge($formInput, [
        'user_id' => Auth::user()->id
    ]));
    foreach ($request->file as $photo) {
        $filename = $photo->store('public/photos');
        ProductsPhoto::create([
            'product_id' => $product->id,
            'filename' => $filename
        ]);
     }
 }

Blade

//The form

 <div class="panel-body">
   <form>
     <input type="hidden" value="" id="token"/>
  <label for="pro_name">Name</label>
  <input type="text" class="form-control" name="pro_name" id="pro_name" placeholder="Enter product name">

    <label for="pro_price">Price</label>
     <input type="text" class="form-control" name="pro_price" id="pro_price" placeholder="Enter price">

 <label for="photos">Choose 5 Images</label>
 <div class="needsclick dropzone" id="document-dropzone">  // Display images preview

  </div>

 <input type="submit" class="btn btn-primary" value="Submit" id="btn"/>

</div>

Ajax

   //This is how I submit the form
    var token = $("#token").val();
    $(document).ready(function(){
        $("#btn").click(function(){
            $("#loading").show();
            var url = '';
            var form = $('form')[0]; 
            var formData = new FormData(form);
            formData.append('_token', token); 
            $.ajax({
                url: url,
                data: formData, 
                type: 'POST',
                cache: false,
                contentType: false, 
                processData: false, 
                success:function(data){
                if($.isEmptyObject(data.error)){
                $("#msg").html("Product has been added successfull");
                $("#msg").fadeOut(3000);
                 window.location.href =  "<?php echo url('seller/product') ?>";
                 $("#loading").hide();
                 }
                 else{

                        printErrorMsg(data.error);

                        }
                }
            });
            function printErrorMsg (msg) {
            $("#loading").hide();
            $(".print-error-msg").find("ul").html('');
            $(".print-error-msg").css('display','block');
            $.each( msg, function( key, value ) {
                $(".print-error-msg").find("ul").append('<li>'+value+'</li>');
            });
            }
        });

    });


   //This is how I get the preview(Dropzone)

     var uploadedDocumentMap = {}
    Dropzone.options.documentDropzone = {
      url: '',
      maxFilesize: 10, // MB
      addRemoveLinks: true,
      headers: {
        'X-CSRF-TOKEN': ""
      },
      success: function (file, response) {
        $('form').append('<input type="hidden" name="document[]" value="' + response.name + '">')
        uploadedDocumentMap[file.name] = response.name
      },
      removedfile: function (file) {
        file.previewElement.remove()
        var name = ''
        if (typeof file.file_name !== 'undefined') {
          name = file.file_name
        } else {
          name = uploadedDocumentMap[file.name]
        }
        $('form').find('input[name="document[]"][value="' + name + '"]').remove()
      },
      init: function () {
        @if(isset($project) && $project->document)
          var files =
            {!! json_encode($project->document) !!}
          for (var i in files) {
            var file = files[i]
            this.options.addedfile.call(this, file)
            file.previewElement.classList.add('dz-complete')
            $('form').append('<input type="hidden" name="document[]" value="' + file.file_name + '">')
          }
        @endif
      }
    }


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire