AM DEV
AM DEV

Reputation: 339

How to arrange <tr> elements of a table using JQuery Sortable

I am new to Laravel and i am trying to make an arrangement of table rows and save their position

In my database I have a table Cars containing attributes id, name, order(int) attributes.

I have the Car model and DataController containing basic crud functions as well as a functions to make the order:

public function orderCars(Request $request){

    $carItemOrder = json_decode($request->input('order'));

    $this->orderItems($carItemOrder);
}

private function orderItems(array $carItems)
{
    foreach ($carItems as $index => $carItem) {
        $item = Car::findOrFail($carItem->id);
        $item->order = $index + 1;
        $item->save();
    }
}

I have my view

<div class="panel-body">

                    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
                    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
                    <script>
                        $(function () {
                            $("tbody").sortable();
                            $("tbody").disableSelection();
                        });
                    </script>

                    <table>
                        <thead>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php $data = App\Car::all();?>
                        @foreach($data as $car)
                            <tr class="dd">
                                <td>{{$car->id}</td>
                                <td>{{ucfirst($car->name)}}</td>
                            </tr>
                        @endforeach
                        </tbody>
                    </table>
                    </div>

I have the route

Route::post('cars/order', ['uses' => 'DataController@orderCars', 'as' => 'car.order']);

What i want to do is order the table rows and save the order in my database but i don't know how to integrate the route with the view and make it work

Upvotes: 1

Views: 558

Answers (1)

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26278

Use update of Jquery UI sortable and make an ajax call to save the data in the database like:

$('#element').sortable({
    axis: 'y',
    update: function (event, ui) {
        var data = $(this).sortable('serialize');

        // POST to server using $.post or $.ajax
        $.ajax({
            data: data,
            type: 'POST',
            url: '/your/url/here'
        });
    }
});

When you use the serialize option, it will create a POST query string like this: item[]=1&item[]=2 etc.

Reference

Upvotes: 1

Related Questions