mosamy/sortable

Laravel package for model sorting

1.0.7 2023-07-09 23:01 UTC

This package is auto-updated.

Last update: 2025-04-10 03:01:07 UTC


README

Make your eloquent model sortable.

Installation

composer require mosamy/sortable
php artisan vendor:publish --provider="Mosamy\Sortable\SortableServiceProvider" --tag="assets"
php artisan migrate

Make sure that you have jquery-ui liberary in your view

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

Make sure that you included the csrf-token meta tag in your view

<meta name="csrf-token" content="{{ csrf_token() }}" />

Make sure that you included the X-CSRF-TOKEN in the ajaxSetup headers

  $.ajaxSetup({
    headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
  });

Usage

Put this after jquery-ui script before the closed header tag or body tag.

@sortJs()

Use the sortable trait inside your model.


namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
  use \Mosamy\Sortable\Sortable;
}

Set a class name sortable-table to your table tag. Put this x-sortable::item in each tr tag inside the loop Put this line x-sortable::type after the table close tag

<table class="sortable-table"> <!--set the class name -->

	<tbody>

		@foreach($list as $item)
		<tr>
			<td>...</td>
			<td>...</td>

			<!--sput this line in each <tr> tag inside the loop -->
			<x-sortable::item :item="$item" />
		</tr>
		@endforeach
	</tbody>
</table>

<!--put this line after close table tag </table> -->
<x-sortable::type :list="$list" />

and that's it!

Now you can drag and drop your list and the sort will be executed automatically.

To get a list with sort you should use this method.

$posts = Post::orderBySort()->get();

Hooks

To perform an action after the sort process completed you can override this method inside the sortable model.


namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
  use \Mosamy\Sortable\Sortable;

  public static function afterSort(){
    // add some code to execute after the sort is completed
  }

}

Config

By default, the draggable sort executes by ajax request at url /sortable/sort with default middleware ['web']

If you need to change this you may publish this config file.

php artisan vendor:publish --provider="Mosamy\Sortable\SortableServiceProvider" --tag="config"

Now you can change the values of url and middleware.

return [
  'url' => 'sortable/sort',
  'middleware' => ['web']
];