Laravel Dynamic Drag and Drop with Jquery Sortable Example; In this tutorial we will show you how to implement drag and drop functionality in laravel using jQuery sortable package to sorting posts, menues, tasks etc. The jQuery sortable package monitoring order to ascending or descending.
Drag and drop is a amazing functionality when you can manually change the custom order in ascending or descending. The most user-case for drag and drop sorting funcationality for a web applicaiton are menu item sorting, person list sorting etc.
Many times we need to make dynamic sorting or drag and drop list items or div or table rows, it is simply and easy things for client or any user to understand flow. We have added the step by step guide for ui sortable the menu, div or table easily understable in laravel application.
Download Laravel App
First at all create new laravel 9 application adding the following command in terminal.
composer create-project --prefer-dist laravel/laravel laravel-sortable
Connect App to Database
Open the .env file and add your database credentials such as database name, username equally important password:
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=db name DB_USERNAME=db user name DB_PASSWORD=db password
Build Model and Migration
Next step, we need to execute the following command on terminal to generate model, migration file using the following command:
php artisan make:model Post -m
Next, open database/migrations/2021_09_26_072241_create_posts_table.php file and update the new value inside the up() method.
<?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->id();
$table->string('title');
$table->text('description');
$table->string('order')->default(0);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
After that, run the following command to migrate the table into select database:
php artisan migrate
Here, you have to register the fillable property inside the fillable array within the app/Models/Post.php file.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $fillable = [
'title', 'description', 'order'
];
}
Define Routes
In this step, Navigate to the app/routes folder then open and update the following code in the routes/web.php file.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
Route::get('posts', [PostController::class, 'index']);
Route::post('update-order', [PostController::class, 'updateOrder']);
Create and Configure Controller
This step consists of generating a new laravel controller and making the controller ready with PHP logic to create dynamic drag and drop sort items using jQuery.
php artisan make:controller PostController
After executing above command a new controller file manifested, now you need to add the following code in app\Http\Controllers\PostController.php this file and then save the file.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
class PostController extends Controller
{
public function index(Request $request){
$posts = Post::orderBy('order','asc')->get();
return view('posts',compact('posts'));
}
public function updateOrder(Request $request){
foreach ($request->order as $key => $order) {
$post = Post::find($order['id'])->update(['order' => $order['order']]);
}
return response('Update Successfully.', 200);
}
}
Create View File
In this last step, we need to create the basic form; we will use Bootstrap 5 and jQuery to create the form that allows the creation of drag and drop items and sort order dynamically.
Hence, open resources/views/posts.blade.php file, and add the following code within the file.
<!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 class="table table-bordered">
<thead>
<tr>
<th width="30px">#</th>
<th>Title</th>
<th>Description</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>{{ $post->description }}</td>
<td>{{ date('d-m-Y h:m:s',strtotime($post->created_at)) }}</td>
</tr>
@endforeach
</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 type="text/javascript">
$(function () {
$( "#tablecontents" ).sortable({
items: "tr",
cursor: 'move',
opacity: 0.6,
update: function(e) {
updatePostOrder();
}
});
function updatePostOrder() {
var order = [];
var token = $('meta[name="csrf-token"]').attr('content');
$('tr.row1').each(function(index, element) {
order.push({
id: $(this).attr('data-id'),
order: index
});
});
$.ajax({
type: "POST",
dataType: "json",
url: "{{ url('posts/update-order') }}",
data: {
order: order,
_token: token
},
success: function(response) {
if (response.status == "success") {
console.log(response);
} else {
console.log(response);
}
}
});
}
});
</script>
</body>
</html>
Generate Dummy Records
Now the all the work is done, Generate dummy records for testing laravel drag and drop menu sorting example. Create a seeder and put the below code on it.
See Here: Generate Fake Data using Faker and Factory in Laravel
database\seeders\PostsTableSeeder.php
<?php namespace Database\Seeders; use Illuminate\Database\Seeder; use Faker\Factory as Faker; use App\Models\Post; class PostsTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $faker = Faker::create(); $limit = 10; for ($i = 0; $i < $limit; $i++) { Post::create([ 'title' => $faker->sentence($nbWords = 6, $variableNbWords = true), 'description' => $faker->paragraph($nbSentences = 3, $variableNbSentences = true), 'order' => $i ]); } } }
Next, open our terminal and run the seeder using the following command:
php artisan db:seed --class=PostsTableSeeder
Start Project and Test
Run to laravel project just put the below command in your teminal.
php artisan serve
then hit to ulr:
http://localhost:8000/posts
So this was it; Laravel Dynamic Drag and Drop items with Jquery Sortable and save to database with ajax. In this tutorial, we have learned how to implement drag and drop funcationaly to update order using jquery and bootstrap in laravel 9 app.