Drag and Droppable Cards By Using Laravel JQuery UI Example

Share Me
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

In this instructional exercise, I will clarify how you can drag and droppable cards utilizing laravel jquery ui.we will show drag and droppable cards utilizing laravel jquery ui model. you can make drag and droppable cards utilizing laravel jquery ui.

Dynamic arranging or simplified rundown cards , it’s astounding things for customer or any client to get stream. On the off chance that you make arranging with intuitive capable cards or div for your Items/item at that point it’s amazing.

I might want to impart to you how to make simplified cards utilizing jquery ui and furthermore we will make it dynamic utilizing laravel 6. so essentially we will save information into data set utilizing jquery ajax. we will utilize bootstrap for simply improve it design. we need to utilize jquery ui for make column. we will utilize cdn jquery ui or css.

So follow underneath step to done this model.

Step 1 : Install Laravel 6 Application

Here i am going from scratch, So now i have required to get fresh Laravel application by using bellow command, So open your terminal OR command prompt and then run bellow command:

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

Database Configuration

Now in this step, we have a require to make database configuration, we need to add following details on your .env file.

1.Database Username

2.Database Password

3.Database Name

So now in .env file also available host and port details, now we can configure all details as in our system, So we can put like as bellow:

following path: .env

DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
Step 2: Create ajax Item Table and Model

Now in this step we need to create a migration for Items table by using Laravel 8 php artisan command, so first fire bellow command:

php artisan make:model Item -m

So after this command we have to put bellow code in your migration file for create Item table.

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');
    }
}

Now we need to run migration by using bellow command:

php artisan migrate

So after that we have to put bellow code in our model file for create Item table.

following path:/app/Models/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

Now in this is step we need to create route for ajax update items status layout file and another one for post request. So open following file path

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

So here in this step now we should create a new controller as ItemController, So need to run bellow command for generate new controller

php artisan make:controller ItemController

So now this step, this controller will manage layout and ajax update items status layout with post request,Just bellow content in controller file. So pest in following file path

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

We are now in Last step, so we need to crate a blade file. so let’s create dragAndDroppable.blade.php(resources/views/dragAndDroppable.blade.php) for layout and now we will write design code here and also Drag and Droppable Cards and ajax to store data items status, So put following code:

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-codingspoint.com</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">codingspoint.com</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>

So now we are ready to run our example so need to run bellow command so quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/

Read Also : Laravel 8 Eloquent Global Scope Tutorial Example

I hope it will help you. Also you can follow us on Facebook

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →