Rainier laan
Rainier laan

Reputation: 1130

Laravel SortableJS AJAX - How to rearrange order

I just implemented SortableJS in my Laravel project and want to rearrange the order of some elements. I have a list of "Blocks" which all have a database field of "Order" which is an integer. I show these blocks in descending order based on the value of the "Order" field.

Now I want to update these values with SortableJS using Ajax. How can I accomplish this?

Currently, I have a simple list

<div class="block-order-list">
   @foreach($blocks as $block)
     <div class="list-group-item"><i class="far fa-arrows handle mr-3"></i> {{$block->name}}</div>
   @endforeach
</div>

And call an Ajax request like so:

$('.block-order-list').sortable({
            animation: 150,
            handle: '.handle',
            store: {
                set: function (sortable) {
                    let order = sortable.toArray();
                    console.log(order);
                    $.ajaxSetup({
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        }
                    });
                    $.ajax({
                        url: '{{ route('change_order', ['url', $page->url]) }}',
                        type: 'POST',
                        data: order,
                        success: function(data){
                            console.log(data)
                        }
                    })
                }
            }
        });

To my PageController which contains

 public function changeOrder($data)
    {

        return $data;
    }

The request now only returns a string that says url which I find odd. In the url of the ajax request, I give a parameter called URL which I need to find the blocks attached to this specific page. My blocks database table looks like this

enter image description here

How can I accomplish this?

Upvotes: 4

Views: 3062

Answers (1)

Vincent Decaux
Vincent Decaux

Reputation: 10714

I guess you must use ID in your HTML list :

<div class="block-order-list">
   @foreach($blocks as $block)
     <div class="list-group-item" data-id="{{ $block->id }}>
          <i class="far fa-arrows handle mr-3"></i> {{ $block->name }}
     </div>
   @endforeach
</div>

Then in your JS, build an array with ID => order :

let order = {};
$('.list-group-item').each(function() {
    order[$(this).data('id')] = $(this).index();
});

Then in your ajax call :

 $.ajax({
    url: '{{ route('change_order', ['url', $page->url]) }}',
    type: 'POST',
    data: {order: order},
    success: function(data){
        console.log(data)
    }
})

And in your controller :

public function changeOrder(Request $request)
{
    foreach($request->get('order') as $id => $order) {
        Block::find($id)->update(['order' => $order]);
    }
}

Upvotes: 6

Related Questions