Hello Devs, 

In this tutorial, we will learn Drag and Droppable Cards using Laravel 7/6 JQuery UI Example

Follow this step by step guide below. 



Step 1 : Install Laravel 6 Application

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


Database Configuration

Add the following things on you .env file

  1. Database Username
  2. Database Password
  3. Database Name

following path: .env

DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret


Step 2: Create ajax Item Table and Model

php artisan make:model Item -m


following path:

/database/migrations/2020_01_10_102325_create_items_table.php

<?php

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

class CreateItemsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('items', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->integer('order');
            $table->tinyInteger('status');
            $table->timestamps();
        });
    }

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


run migration from below command :

php artisan migrate


following path:/app/Item.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'title', 'order', 'status',
    ];
}


Step 4: Create Route

following path:/routes/web.php

Route::get('/', array('as'=> 'front.home', 'uses' => 'ItemController@itemView'));
Route::post('/update-items', array('as'=> 'update.items', 'uses' => 'ItemController@updateItems'));


Step 5: Create Controller

php artisan make:controller ItemController


following path:/app/Http/Controllers/ItemController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Item;

class ItemController extends Controller
{

    public function itemView()
    {
    	$panddingItem = Item::where('status',0)->orderBy('order')->get();
    	$completeItem = Item::where('status',1)->orderBy('order')->get();

    	return view('dragAndDroppable',compact('panddingItem','completeItem'));
    }

    public function updateItems(Request $request)
    {
    	$input = $request->all();

    	foreach ($input['panddingArr'] as $key => $value) {
    		$key = $key+1;
    		Item::where('id',$value)->update(['status'=>0,'order'=>$key]);
    	}

    	foreach ($input['completeArr'] as $key => $value) {
    		$key = $key+1;
    		Item::where('id',$value)->update(['status'=>1,'order'=>$key]);
    	}

    	return response()->json(['status'=>'success']);
    }

}



Step 6: Create View

following path:resources/views/dragAndDroppable.blade.php

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <title>jQuery UI Draggable - Default functionality-rathorji.in</title>

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

  <style>
    #draggable { 
        width: 150px;
        height: 150px;
        padding: 0.5em;
    }
  </style>
</head>
<body class="bg-light">
<div class="container">
  <div class="row">
    <div class="col-md-12">
        <h2 class="text-center pb-3 pt-1">Drag and Droppable Cards using Laravel 6 JQuery UI Example <span class="bg-success p-1">rathroji.in</span></h2>
        <div class="row">
            <div class="col-md-5 p-3 bg-dark offset-md-1">
                <ul class="list-group shadow-lg connectedSortable" id="padding-item-drop">
                  @if(!empty($panddingItem) && $panddingItem->count())
                    @foreach($panddingItem as $key=>$value)
                      <li class="list-group-item" item-id="{{ $value->id }}">{{ $value->title }}</li>
                    @endforeach
                  @endif
                </ul>
            </div>
            <div class="col-md-5 p-3 bg-dark offset-md-1 shadow-lg complete-item">
                <ul class="list-group  connectedSortable" id="complete-item-drop">
                  @if(!empty($completeItem) && $completeItem->count())
                    @foreach($completeItem as $key=>$value)
                      <li class="list-group-item " item-id="{{ $value->id }}">{{ $value->title }}</li>
                    @endforeach
                  @endif
                </ul>
            </div>
        </div>
    </div>
  </div>
</div>
  <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

  <script>
  $( function() {
    $( "#padding-item-drop, #complete-item-drop" ).sortable({
      connectWith: ".connectedSortable",
      opacity: 0.5,
    }).disableSelection();

    $( ".connectedSortable" ).on( "sortupdate", function( event, ui ) {
        var panddingArr = [];
        var completeArr = [];

        $("#padding-item-drop li").each(function( index ) {
          panddingArr[index] = $(this).attr('item-id');
        });

        $("#complete-item-drop li").each(function( index ) {
          completeArr[index] = $(this).attr('item-id');
        });

        $.ajax({
            url: "{{ route('update.items') }}",
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            data: {panddingArr:panddingArr,completeArr:completeArr},
            success: function(data) {
              console.log('success');
            }
        });
          
    });
  });
</script>
</body>
</html>


Run below command for a peek

php artisan serve


Open this URL in your browser: 

http://localhost:8000/


May this example help you.