Drag and Drop Datatable Rows for Sorting in Laravel 8

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
Drag and Drop Datatable Rows for Sorting Example in Laravel 8

Today now in this tutorial, I will show how we can use jQuery UI Sortable alos along with Datatables to add drag and drop functionality in laravel 8 application. Now this is an example of drag and drop database table rows for sorting laravel 8 application.

So this is dynamic sorting or drag and drop list items or div or table rows. It is very simple and also very easy things for client or any user to understand flow.

Now here I will also try to make this tutorial very basic so that everyone can easily follow this step by step. Also all of you need to know is a basic of jQuery and Laravel.

step 1: Install Laravel Project

At first, we need to download a laravel fresh setup. By use this command we can download laravel project setup :

composer create-project --prefer-dist laravel/laravel blog
step 2: Setup Database

So after the successfully install laravel 8 Application, So go to your project .env file and set up your database credential and then 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 
step 3: Create Migration

So now we will create a table as posts then follow this command in your terminal:

php artisan make:migration create_posts_table 

Now by use this command will create migration file for the posts table.

database/migrations/create_posts_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

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

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

Now in next,by use this command to in your terminal and then this setup create to in your database.

php artisan migrate
step 4: Create Model

So in this step,we need to create to model in project. By use bellow this command :

php artisan make:model Post

Now it will create to file in app/Model/Post.php model.

app/Model/Post.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'title', 'order'
    ];
}
step 5: Make Route

So now we will need to create route in web.php file.

routes/web.php

//PostController
Route::get('post','PostController@index');
Route::post('post-sortable','PostController@update');
step 6: Create Controller

Now we need to create a new controller name PostController. By this command use to your terminal.

php artisan make:controller PostController

Then after the create to methods:

The first method will be index(), it will show you post.

Now the second method will be update(), it will update your post event into database.

app/Http/Controllers/PostController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Model\Post;

class PostController extends Controller
{
    public function index()
    {
        $posts = Post::orderBy('order','ASC')->get();

        return view('post',compact('posts'));
    }

    public function update(Request $request)
    {
        $posts = Post::all();

        foreach ($posts as $post) {
            foreach ($request->order as $order) {
                if ($order['id'] == $post->id) {
                    $post->update(['order' => $order['position']]);
                }
            }
        }
        
        return response('Update Successfully.', 200);
    }
}
step 7: Create View File

So in this step we need to create blade view file.

resources/views/post.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Create Drag and Droppable Datatables Using jQuery UI Sortable 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"/>
</head>
<body>
    <div class="row mt-5">
        <div class="col-md-10 offset-md-1">
            <h3 class="text-center mb-4">Drag and Drop Datatables Using jQuery UI Sortable - Demo </h3>
            <table id="table" class="table table-bordered">
              <thead>
                <tr>
                  <th width="30px">#</th>
                  <th>Title</th>
                  <th>Created At</th>
                </tr>
              </thead>
              <tbody id="tablecontents">
                @foreach($posts as $post)
    	            <tr class="row1" data-id="{{ $post->id }}">
    	              <td class="pl-3"><i class="fa fa-sort"></i></td>
    	              <td>{{ $post->title }}</td>
    	              <td>{{ date('d-m-Y h:m:s',strtotime($post->created_at)) }}</td>
    	            </tr>
                @endforeach
              </tbody>                  
            </table>
            <hr>
            <h5>Drag and Drop the table rows and <button class="btn btn-success btn-sm" onclick="window.location.reload()">REFRESH</button> the page to check the Demo.</h5> 
    	</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 type="text/javascript">
      $(function () {
        $("#table").DataTable();

        $( "#tablecontents" ).sortable({
          items: "tr",
          cursor: 'move',
          opacity: 0.6,
          update: function() {
              sendOrderToServer();
          }
        });

        function sendOrderToServer() {
          var order = [];
          var token = $('meta[name="csrf-token"]').attr('content');
          $('tr.row1').each(function(index,element) {
            order.push({
              id: $(this).attr('data-id'),
              position: index+1
            });
          });

          $.ajax({
            type: "POST", 
            dataType: "json", 
            url: "{{ url('post-sortable') }}",
                data: {
              order: order,
              _token: token
            },
            success: function(response) {
                if (response.status == "success") {
                  console.log(response);
                } else {
                  console.log(response);
                }
            }
          });
        }
      });
    </script>
</body>
</html>
step 8: Run Development Server

Now we can run to laravel project in our terminal. By use bellow command

php artisan serve

then make to ulr:

localhost:8000/post

Read Also : Laravel 8 Eloquent Global Scope Tutorial Example

I hope it will help you. Also you can follow us on Facebook

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →