I'm trying to make a sortable table in my laravel app where the order also needs to be updated in the database, I'm trying to do it with jquery, ajax.
I tried to figure it out with this pieces of code:
JQuery/Ajax
$(document).ready(function () {
        $('table tbody').sortable({
            update: function (event, ui) {
                $(this).children().each(function (index) {
                    if ($(this).attr('data-position') != (index + 1)) {
                        $(this).attr('data-position', (index + 1)).addClass('updated');
                    }
                });
                saveNewPositions();
            }
        });
    });
    function saveNewPositions() {
        var positions = [];
        $('updated').each(function () {
            position.push([$(this).attr('data-index'), $(this).attr('data-position')]);
            $(this).removeClass('updated');
        });
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $.ajax({
            url: 'cursos',
            method: 'POST',
            dataType: 'text',
            data: {
                'updated': 1,
                'positions': positions,
                '_token': '{{ csrf_token() }}'
            },
        })
Then in my web.php I created a post route:
Route::post('/cursos', function (Request $request){
return SectionCourseController::updateOrder($request);})->name('post');
In my controller I created this function:
        public static function updateOrder(Request $request)
{
    var_dump($request->positions);
    foreach ($request->positions as $position) {
        $index = $position[0];
        $newPosition = $position[1];
        $seccion = SectionCourse::findOrFail($index);
        $seccion->order = $newPosition;
        $seccion->save();
    }
    return response('success', 200);
}
When I'm trying to update the order, I'm having an error on the console of 500 (Internal Server Error).
[2022-06-14 14:16:18] local.ERROR: foreach() argument must be of type array|object, null given {"userId":1,"exception":"[object] (ErrorException(code: 0): foreach() argument must be of type array|object, null given
Sorry if I'm doing something bad on Ajax, this is the first time I try to do something on it.
 
     
     
    