cezi7's avatar
Level 1

Sortable images with jQuery ui-sortable and Laravel

Hello. I want to insert multiple images and before upload them I want to sort them so the user can choice the first image. This is my jquery:

$( "#sortable" ).sortable({ update:function(event, ui) { event.preventDefault(); $.ajax({ type:'POST', url:'{{ route('vehiculos.store') }}', data: $(this).sortable('serialize'), success:function(data){ alert(data.success); }, error : function() { alert('error...'); } }); } });

And my Controller where I upload the images:

if($request->hasFile('imagenes')){

        foreach($files as $file){
            
            $filename = $file->getClientOriginalName();     
            
            $vehiculo->imagenes .= $file->storeAs($folder, $filename) ."@";
                            
        }                           
    }

I don't know what else to put in my controller. When I try to sort the images I recieve this error via console: 422(Unprocessable Entity). Thank you.

0 likes
4 replies
cezi7's avatar
Level 1

@TomyLimon this is the part where I upload the files

  <input type="file" name="imagenes[]" id="imagenes" multiple>  <br>
  <ul class="preview-gallery" id="sortable"></ul>

and this is the jquery to preview the uploaded files

$(function() {var imagesPreview = function(input, placeToInsertImagePreview) {

  if (input.files) {

    var filesAmount = input.files.length;

    for (i = 0; i < filesAmount; i++) {

      var count = 1;

      var reader = new FileReader();

      reader.onload = function(event) {  
   
        $($.parseHTML('<li class="ui-state-default"><img>')).attr('src',event.target.result).attr('class', 'img-item').attr('id',count).appendTo(placeToInsertImagePreview);

        $($.parseHTML('</li>'));
       count++;

      }
      reader.readAsDataURL(input.files[i]);
    }
  }

};

$('#imagenes').on('change', function() {
  imagesPreview(this, 'ul.preview-gallery');
});

});

TomyLimon's avatar

Ok. Here is a problem. You try to send information with no csrf_token

You need add csrf to your request. Add this line in your layout.blade.php header section

<html>
<heade>
...
<meta name="csrf-token" content="{{ csrf_token() }}" />
...

Add this line in your JS file

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

Please or to participate in this conversation.