- Drag and Drop feature make web page user-friendly and provides a good user interface for the web application.
- Using jQuery and jQuery UI library, the drag & drop functionality can be implemented easily.
- If you’re developing a web application that listing task or items, then you can easily drag & drop functionality in your web application to increase user experience.
- We will also use MySQL database table to display items and also order of items after drag and drop reorder.
- So in this article you will learn how to implement drag & drop functionality in PHP Laravel.
1. Make Php Page
<div class="task_box"> <div class="column" id="pending"> <h1>All Tasks</h1> @foreach($pending_tasks as $task) <div class="list-group-item" data-id="{{ $task->id }}" draggable="true" >{{ $task->name }}</div> @endforeach </div> <div class="column" id="progress"> <h1>In progress</h1> @foreach($progress_tasks as $task) <div class="list-group-item" data-id="{{ $task->id }}" draggable="true" >{{ $task->name }}</div> @endforeach </div> <div class="column" id="complete"> <h1>Completed</h1> @foreach($complete_tasks as $task) <div class="list-group-item" data-id="{{ $task->id }}" draggable="true">{{ $task->name }}</div> @endforeach </div> </div> |
2. Define Script
<script src= "https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.14.0/Sortable.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script> |
And sortable() function to perform sorting or reordering using Ajax.
<script type="text/javascript"> $('.column').sortable({ connectWith: '.column', ghostClass: "blue-background-class", }); $('.list-group-item').click(function (event) { event.preventDefault();
var id = $(this).attr('data-id'); var status = $(this).parent().attr('id'); $.ajax({ url: "<?php echo URL('/update_task') ?>", data: 'status=' + status + '&id=' + id, type: "get", success: function (data) { alert(data); } }); }); </script> |
3. Route
Route::get('update_task', [MyTaskController::class, 'update_task'])->name('update_task'); |
4. PHP Script(Controller)
public function index(Request $request) { $pending_tasks = Task::where('status', 'pending') ->orderBy('id', 'DESC')->get(); $progress_tasks = Task::where('status', 'progress') ->orderBy('id', 'DESC')->get(); $complete_tasks = Task::where('status', 'complete') ->orderBy('id', 'DESC')->get(); return view('my_tasks', compact('pending_tasks', 'progress_tasks', 'complete_tasks')); }
public function update_task(Request $request, Task $task) { $status = $request->get('status'); $id = $request->get('id');
$task = Task::find($id); $task->status = $status; $task->save(); return 'Task Update successfully.'; } |
In this article, we first fetched items from the database and created a dynamic jQuery drag & drop todo list and applied drag & drop feature.
Finally, as the item is dropped, the status of the item is updated in the database table using an AJAX request to the server.