Drag and drop the datatable's row in laravel

In this article, I will share with you how to Drag and drop the datatable's row in laravel.

We are going to Configure Laravel Project.

#1: Install Laravel Project

Install Laravel Project by the typing following command.

$ composer create-project --prefer-dist laravel/laravel laravelDragAndDrop

#2: Setup Database

After successfully install laravel Application, Go to your project .env file and set up database credential and move next step :

DB_CONNECTION=mysql 
DB_HOST=127.0.0.1 
DB_PORT=3306 
DB_DATABASE=here your database name 
DB_USERNAME=here database username
DB_PASSWORD=here database password 

#3 : Install Required Packages

We have required following packages for integrate yajra datatable in our laravel application.

composer require yajra/laravel-datatables-oracle:"~9.0"

Register provider and facade on your config/app.php file.

'providers' => [
    ...,
    Yajra\DataTables\DataTablesServiceProvider::class,
]

'aliases' => [
    ...,
    'DataTables' => Yajra\DataTables\Facades\DataTables::class,
]

then after run following command in your terminal

php artisan vendor:publish --provider="Yajra\DataTables\DataTablesServiceProvider"

#4: Create Migration

Now we will create a table products then follw this command in your terminal:

php artisan make:migration create_products_table

It command will create migration file for the products table.

database/migrations/create_products_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('products_name');
            $table->string('products_category');
            $table->integer('products_quantity');
            $table->integer('order')->default(0);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}

Next,this command use to in your terminal then this setup create to in your database.

php artisan migrate

#5: Create a Model

Next,you will create to model in project bellow this command : 

php artisan make:model Products

It will create to file in app/Products.php model.

app/Products.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Products extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'products_name', 'products_category','products_quantity','order'
    ];
}

#6: Define Route

We register all route in a web.php file.

Route::get('products','ProductsController@index');
Route::get('datatable', 'ProductsController@listDataTable')->name('products.datatable');
Route::post('products-sorting','ProductsController@updateOrder')->name('sort.products');

#7: Create a Controller 

php artisan make:controller ProductsController

It will build a controller file called ProductsController.php.

app/Http/Controllers/ProductsController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Products;
class ProductsController extends Controller
{
    public function index()
    {
        return view('products');
    }

    public function listDataTable(){
        $data = Products::all();
        return \Yajra\DataTables\DataTables::of($data)
            ->setRowAttr([
                'data-id' => function($data) {
                    return $data->id;
                },
            ])
            ->make(true);
    }

    public function sortRules(request $request)
    {
        try {
            $rules = Products::all();
            foreach ($rules as $task) {
                $id = $task->id;
                foreach ($request->order as $key=>$order) {
                    Products::where("id",$order["id"])->update(['order' => $order['position']]);
                }
            }
            return response()->json([
                'success' => true,
            ]);
        } catch (Exception $e) {
            return response()->json([
                'success' => false,
            ]);
        }

    }

}

The first method is index(), it will show you Products view page.
The second method is listDataTable(), it will fetch the products data into database.
The third method is updateOrder(), it will update your postition event into database. 

#8: Create View File

In this step you need to create blade view file.

resources/views/products.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Drag and drop the datatable's row in laravel</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.12/datatables.min.css"/>
    <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"/>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/build/css/alertify.min.css"/>
</head>
<body>
    <div class="row mt-5">
        <div class="col-md-10 offset-md-1">
            <h3 class="text-center mb-4">Drag and drop the datatable's row in laravel - Demo </h3>
            <table id="product_List" class="table table-bordered">
              <thead>
                <tr>
                  <th width="30px">#</th>
                  <th>Product Title</th>
                  <th>Product Category</th>
                  <th>Product Quantity</th>
                  <th>Order</th>
                </tr>
              </thead>
              <tbody id="tableContents">
                
              </tbody>                  
            </table> 
        </div>
    </div>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.12/datatables.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/build/alertify.min.js"></script>
    <script type="text/javascript">
      $(function () {
        $('#product_List').DataTable({
            dragColumn:true,
            ajax: '{{route("products.datatable")}}',
            columns: [
                {data: 'id', name: 'id'},
                {data: 'products_name', name: 'products_name'},
                {data: 'products_category', name: 'products_category'},
                {data: 'products_quantity', name: 'products_quantity'},
                {data: 'order', name: 'order'},
            ],
            "order": [[ 4, "asc" ]]
        });

        $( "#tableContents" ).sortable({
            items: "tr",
            cursor: 'move',
            opacity: 0.6,
            update: function() {
                sendOrderToServer();
            }
        });
        
        function sendOrderToServer() {
            var order = [];
            $('#product_List tbody>tr').each(function(index,element) {
                order.push({
                    id: $(this).attr('data-id'),
                    position: index+1
                });
            });
        $.ajax({
            type: "POST", 
            dataType: "json", 
            url: "{{route('sort.products')}}",
            data: {
                order:order,
                _token: '{{csrf_token()}}'
            },
            success: function(data) {
                if(data.success == true) {
                  alertify.success('Priority set Successfully  !!');
                }
                else
                {
                  alertify.error('Something Went Wrong !!');
                }
                $("#product_List").DataTable().ajax.reload();
            }
        });        
    }
    </script>
</body>
</html>

#9: Run Development Server

you can run to laravel project in your teminal.bellow command:

php artisan serve

I hope it will help you.