Drag and Drop Datatable Rows for Sorting Re-Ordering in Laravel
By Ved Prakash N |
Feb 21, 2023 |
Laravel
Laravel: Re-Ordering with Drag/Drop using DataTables and jQuery
In this tutorial, I will show how to use jQuery UI Sortable along with Datatables to add drag and drop functionality in laravel 6/7/8/9/10.
This is an example of drag and drop datatable rows for sorting posts data in laravel.
We will be using Bootstrap 5 for user interface and dataTable too.
Dynamic sorting or Re-ordering the positions or drag and drop list items or div or table rows.
All you need to know is basic of jQuery and Laravel to build this functionality.
Step 1: Install Laravel Project
composer create-project laravel/laravel projectname
Step 2: Setup Database
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your database
DB_USERNAME=your username
DB_PASSWORD=your password
Step 3: Create Migration by following command:
php artisan make:migration create_posts_table
After successful of migration for the posts table go to database/migrations/2023_01_0645_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');
}
}
Once, you are done with above changes in your posts table. run the below command to migrate the tables into your database.
php artisan migrate
Step 4: Create Model by following command:
php artisan make:model Post
after successfully of above command. It will create a file in the following path app/Models/Post.php
add the following as shown below:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $table = 'posts';
protected $fillable = [
'title',
'order'
];
}
Step 5: Make Routes
let's go to web.php file to create routings as follows : routes/web.php
Route::get('post', [App\Http\Controllers\PostController::class, 'index']);
Route::post('post-reorder', [App\Http\Controllers\PostController::class, 'reorder']);
Step 6: Create Controller by the following command:
php artisan make:controller PostController
after successful of above command. It will create a file in following path : app/Http/Controllers/PostController.php
and update the changes
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
class PostController extends Controller
{
public function index()
{
$posts = Post::orderBy('order','ASC')->get();
return view('posts.index', compact('posts'));
}
public function reorder(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(['message' => 'Update Successfully'], 200);
}
}
Step 7: Create Blade File as follows
go to resources/views/ and then create a folder named posts and inside that posts folder create index.blade.php and paste as given below .
<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Create Drag and Droppable Datatables Using jQuery UI Sortable in Laravel</title>
<!-- Bootstrap 5 CDN Link -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Database CSS link ( includes Bootstrap 5 ) -->
<link href="https://cdn.datatables.net/1.13.2/css/dataTables.bootstrap5.min.css" rel="stylesheet" />
<!-- Font Awesome Icons -->
<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="container mt-5">
<div class="row justify-content-center">
<div class="col-md-10">
<h3 class="text-center mb-4">Drag and Drop Datatables ROWS Using jQuery UI Sortable in Laravel </h3>
<table id="table" class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th width="30px">#</th>
<th>Title</th>
<th>Created At</th>
</tr>
</thead>
<tbody id="tableBodyContents">
@foreach($posts as $post)
<tr class="tableRow" data-id="{{ $post->id }}">
<td class="pl-3">
<i class="fa fa-bars"></i>
</td>
<td>{{ $post->title }}</td>
<td>{{ date('d-m-Y h:m:s',strtotime($post->created_at)) }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
<!-- jQuery CDN Link -->
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<!-- Bootstrap 5 Bundle CDN Link -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
<!-- jQuery UI CDN Link -->
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<!-- DataTables JS CDN Link -->
<script src="https://cdn.datatables.net/1.13.2/js/jquery.dataTables.min.js"></script>
<!-- DataTables JS ( includes Bootstrap 5 for design [UI] ) CDN Link -->
<script src="https://cdn.datatables.net/1.13.2/js/dataTables.bootstrap5.min.js"></script>
<script type="text/javascript">
$(function () {
$("#table").DataTable();
$("#tableBodyContents").sortable({
items: "tr",
cursor: 'move',
opacity: 0.6,
update: function() {
sendOrderToServer();
}
});
function sendOrderToServer() {
var order = [];
var token = $('meta[name="csrf-token"]').attr('content');
$('tr.tableRow').each(function(index,element) {
order.push({
id: $(this).attr('data-id'),
position: index+1
});
});
$.ajax({
type: "POST",
dataType: "json",
url: "{{ url('post-reorder') }}",
data: {
order: order,
_token: token
},
success: function(response) {
if (response.status == "success") {
console.log(response);
} else {
console.log(response);
}
}
});
}
});
</script>
</body>
</html>
Step 7: Run Development Server with the following command:
php artisan serve
Open the URL after serve
http://localhost:8000/posts
and now you can start changing the Post Positions / re-ordering the data
It will help you. Thank you for reading.