Drag and Drop reorder row position using jQuery UI Sortable in Laravel

By Ved Prakash N | Apr 01, 2023 | Laravel
Share :

https://www.fundaofwebit.com/post/drag-and-drop-reorder-row-position-using-jquery-ui-sortable-in-laravel

Drag and Drop reorder row position using jQuery UI in Laravel


In this post, you will be learning how to re order position / drag and drop for reorder row position using jquery in laravel 10 /9 /8 /7 /6

This is a example of Drag and Drop Rows for Sorting in order wise in laravel. 

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.

So guys, let get started.

Step 1: Install Laravel Project.

composer create-project --prefer-dist laravel/laravel blog


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 using the following artisan cmd:

php artisan make:migration create_posts_table

once, the migration is successful. It will crreate a migration file for posts. lets open posts table in following path : database/migrations/create_posts_table.php and paste the below code.

<?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 the posts column details are added, lets migrate it in the database by following command:

php artisan migrate


Step 4: Create Model

Now, lets create a model for Posts by the following command. 

php artisan make:model Post

once the Model is created. Lets go to the file : app/Models/Post.php and open the Post.php file and paste the below code:

<?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 Route in routes/web.php

Route::get('/posts', [App\Http\Controllers\PostController::class, 'index']);
Route::post('posts/reorder', [App\Http\Controllers\PostController::class, 'reorder']);


Step 6: Create Controller

create a controller named PostController by thee following artisan command:

php artisan make:controller PostController

 once, the controller created successsfully, let go to path: app\Http\Controllers\PostController.php file and paste thee below code

<?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('Update Successfully.', 200);
    }
}


Step 7: Create View / Blade File

First, we need to add these links and scripts tags & also "yield the content and scripts" as [ @yield('content) , @yield('scripts) ] in app.blade.php files

<!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>{{ config('app.name', 'Laravel') }}</title>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">

    <link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha2/dist/css/bootstrap.min.css" rel="stylesheet" />

</head>
<body>

    <div id="app">

        <main class="py-4">
            @yield('content')
        </main>

    </div>

    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>

    <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha2/dist/js/bootstrap.bundle.min.js"></script>


    @yield('scripts')

</body>
</html>

Now, Lets create a blade view file ( index.blade.php ) in following path : resources/views/posts/index.blade.php

@extends('layouts.app')

@section('content')

<div class="container">
    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h4>Drag and Drop re-order row position using jQuery UI Sortable in Laravel</h4>
                </div>
                <div class="card-body">

                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th width="30px">#</th>
                                <th>Posts</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody id="tableBodyContents">
                            @foreach ($posts as $post)
                            <tr class="tableRow" data-id="{{ $post->id }}">
                                <td class="text-center">&#9776;</td>
                                <td>{{ $post->tite }}</td>
                                <td>{{ $post->created_at->format('d-m-Y') }}</td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>

                </div>
            </div>
        </div>
    </div>
</div>


@endsection

@section('scripts')

    <script type="text/javascript">

        $(document).ready(function () {

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

            function updateOrderPosition() {

                var orderPosition = [];
                var token = $('meta[name="csrf-token"]').attr('content');

                $('tr.tableRow').each(function(index,element) {
                    orderPosition.push({
                        id: $(this).attr('data-id'),
                        position: index+1
                    });
                });

                $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: "{{ url('/posts/reorder') }}",
                    data: {
                        order: orderPosition,
                        _token: token
                    },
                    success: function(response) {
                        if (response.status == "success") {
                            console.log(response);
                        } else {
                            console.log(response);
                        }
                    }
                });
            }
        });
    </script>

@endsection


Step 8: Run Development Server by the following command:

php artisan serve

once, the application is serve is the started, then go to url:

http://localhost:8000/posts


You are all set, now you can drag and drop to re-order the position of posts.

Thanks

https://www.fundaofwebit.com/post/drag-and-drop-reorder-row-position-using-jquery-ui-sortable-in-laravel

Share this blog on social platforms