We noticed you're using an ad blocker

Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Laravel 6 drag and drop menu sorting

world cup 2022

FootballDesk

Get update standing EPL, UEFA, LaLiga and more

Get Now

In a web application, Drag and drop sorting functionality is such an amazing feature when you need to represent the data with custom order without ascending or descending. It gives your user more flexibility to sort their data in a custom sorting order. The most use-case for drag and drop sorting functionality for a web application are menu item sorting, person list sorting, designation list sorting and anything user wants to sort their sorting order. If you are here to read this, then you might be finding an easy and simple way to add drag and drop sorting functionality in your Laravel 6 application. Don't worry, it's not so complex to implement and I'll show you an easy and simple step by step guide on how you can add drag and drop sorting functionality in your Laravel application.

Note: Here I'll show you how to make a drag and drop menu sorting with Laravel 6 and jQuery UI. You can do your self whatever laravel version you are using now. There is no laravel version dependent code. So let's start.

Menu table example data

 id  lable   link    sort_id  
------  ------  ------  ---------
     1  Home    /home           1
     2  Contact /contact        5
     3  About   /about-u        2
     4  Service /service        4
     5  Gallery /gallery        3

Laravel Drag and Drop Sorting

  1. Add jQuery and jQuery UI
  2. Define routes
  3. Make menu controller
  4. Make menu view
  5. Do Js code for Drag and Drop sorting

 

Step 01: Add jQuery and jQuery UI

Add the jQuery and jQuery UI library in your template layout file.

<script src="https://unpkg.com/jquery@2.2.4/dist/jquery.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<link href="https://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css"/>

 

Step 2: Define routes

Define 2 routes in your web.php. If you are using an older version of laravel then it'll be app/Http/routes.php

Route::get('menu/index','MenuController@index');
Route::post('menu/update-order','MenuController@updateOrder'); 

 

Step 3: Make Menu Controller

Make a menu controller by artisan command and do code for sorting the menu in custom sorting order.

php artisan make:controller MenuController
<?php

namespace App\Http\Controllers;

use App\Menu;
use Illuminate\Http\Request;


class MenuController extends Controller
{
    public function index(Request $request){
        $data = Menu::orderBy('sort_id','asc')->get();
        return view('menu',compact('data'));
    }

    public function updateOrder(Request $request){
        if($request->has('ids')){
            $arr = explode(',',$request->input('ids'));
            
            foreach($arr as $sortOrder => $id){
                $menu = Menu::find($id);
                $menu->sort_id = $sortOrder;
                $menu->save();
            }
            return ['success'=>true,'message'=>'Updated'];
        }
    }
}

 

Step 4: Make menu view

Make a view file in resources/views directory name with menu.blade.php

@extends('layouts.app')
@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-4">

            <ul class="sort_menu list-group">
                @foreach ($data as $row)
                <li class="list-group-item" data-id="{{$row->id}}">
                    <span class="handle"></span> {{$row->label}}</li>
                @endforeach
            </ul>

        </div>
    </div>
</div>
<style>
    .list-group-item {
        display: flex;
        align-items: center;
    }

    .highlight {
        background: #f7e7d3;
        min-height: 30px;
        list-style-type: none;
    }

    .handle {
        min-width: 18px;
        background: #607D8B;
        height: 15px;
        display: inline-block;
        cursor: move;
        margin-right: 10px;
    }
</style>
@endsection

 

Step 05: Do Js code for Drag and Drop sorting

At the end of menu.blade.php file before @endsection add these piece of code to make your menu list drag and drop sorting.

<script>
    $(document).ready(function(){

    	function updateToDatabase(idString){
    	   $.ajaxSetup({ headers: {'X-CSRF-TOKEN': '{{csrf_token()}}'}});
    		
    	   $.ajax({
              url:'{{url('/menu/update-order')}}',
              method:'POST',
              data:{ids:idString},
              success:function(){
                 alert('Successfully updated')
               	 //do whatever after success
              }
           })
    	}

        var target = $('.sort_menu');
        target.sortable({
            handle: '.handle',
            placeholder: 'highlight',
            axis: "y",
            update: function (e, ui){
               var sortData = target.sortable('toArray',{ attribute: 'data-id'})
               updateToDatabase(sortData.join(','))
            }
        })
        
    })
</script>

 

I hope, this step by step drag and drop sorting tutorial will help you to add drag and drop sorting functionality in your Laravel application. If you find this helpful then please share this tutorial with others.

 

Share on




Related Post - Latest Post


Tinkerpad - A minimal Laravel code editor

What's new in Laravel 9

Make laravel site super fast by page-cache!

Laravel maintenance mode bypass by Secret Route!

Laravel database backup automatically - cPanel shared hosting, VPS

Laravel Datatables - Ajax, Column, Buttons, Customization