twg_

Drag and Drop sorting

Posted 1 week ago by twg_

I have setup sortable with jQuery UI and I'm able to drag and drop the items in any order I want. What I'm having issues with is saving the order after I move each item.

web.php

Route::prefix('manage')->group(function () {
    Route::prefix('pages')->group(function () {
        Route::post('/reposition', '[email protected]');
    });
});

[email protected]

public function submit(Request $request)
{
        dd($request->all());

        if ($request->has('item')) {
            $i = 0;

            foreach ($request->get('item') as $id) {
                print_r($id); die();
                $i++;
                $page = \App\Page::find($id);
                $page->menu_order = $i;
                $page->save();
            }

            return response()->json(array('success' => true));
        } else {
            return response()->json(array('success' => false));
        }
 }

Blade File (index.blade.php)

<div id="pages">
@foreach($pages as $page)
<div class="page" id="{{ $page->id }}">
    <div class="handle"></div>
    <div class="page-details">
        DETAILS HERE
    </div>
</div>
@endforeach
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script type="text/javascript">
    $('#pages').sortable({
        'containment': 'parent',
        'revert': true,
        helper: function(e, div) {
            var $originals = div.children();
            var $helper = div.clone();
            $helper.children().each(function(index) {
                $(this).width($originals.eq(index).width());
            });
            return $helper;
        },
        handle: '.handle',
        update: function(event, ui) {
            var url = '{{ route("pages.reposition", ":id") }}';
            url = url.replace(':id', ui.item.attr('id'));
            $.post(
                url,
                $(this).sortable('serialize'),
                function(data) {
                    if (!data.success) {
                        alert('Whoops, something went wrong.');
                    }
                },
                'json'
            );
        }
    });
</script>

Please sign in or create an account to participate in this conversation.