Install Dependencies
Firstly, let's install the dependency with a composer package manager.
composer require optimistdigital/nova-sortable
php artisan make:migration add_sort_order_to_posts_table --table=posts
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddSortOrderToPostsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('posts', function (Blueprint $table) { $table->integer('sort_order')->default(1); }); // set default sort order (make use of the ID to sort order) \DB::statement('UPDATE posts SET sort_order = id'); } }
Nova Sort Model Implementation
Since by default this library makes use of the Spatie eloquent-sortable package, we have to add the interface and trait to the model we are going to be sorting. In this case, it's the "Post" model.
<?php namespace App\Models; use Spatie\EloquentSortable\Sortable; use Illuminate\Database\Eloquent\Model; class Post extends Model implements Sortable { use SortableTrait; public $sortable = [ 'order_column_name' => 'sort_order', 'sort_when_creating' => true, ]; # other codes ommited }
<?php namespace App\Nova; use OptimistDigital\NovaSortable\Traits\HasSortableRows; class Post extends Resource { use HasSortableRows; # other codes ommited }
If you refresh the dashboard, now the sorting icon should appear on each and every row for the particular model. By dragging it up and down, the sort order will automatically be updated in the backend.


Has Many Relationship
If there's a scenario where you have to sort on a has many relationships, you will have to pass on the "sort_on_has_many" config and you can define it as follows in the model's declaration.
public $sortable = [ 'order_column_name' => 'sort_order', 'sort_when_creating' => true, 'sort_on_has_many' => true, ];