davidgut/sortable

A sortable trait for Laravel models

Installs: 1

Dependents: 0

Suggesters: 0

Security: 0

Stars: 2

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/davidgut/sortable

v2.0.0 2025-12-16 00:41 UTC

This package is auto-updated.

Last update: 2025-12-20 07:22:07 UTC


README

Simple drag-and-drop sorting for your Laravel models.

Installation

composer require davidgut/sortable

Setup

  1. Add the column to your table. By default, the package looks for a position column.

    Schema::create('posts', function (Blueprint $table) {
        // ...
        $table->integer('position')->nullable();
    });
  2. Implement the Contract and Trait in your Model.

    use DavidGut\Sortable\Contracts\Sortable;
    use DavidGut\Sortable\Traits\HasPosition;
    
    class Post extends Model implements Sortable
    {
        use HasPosition;
    
        // Optional configuration
        // protected $positionColumn = 'custom_order';
        // protected $positionScope = 'category_id'; // Sorts uniquely per category
    }
  3. Add the API Route. Add the following to your routes/web.php or routes/api.php to handle updates.

    use DavidGut\Sortable\Http\Controllers\PositionController;
    
    Route::put('/sortable/{model}/{id}', PositionController::class)->name('sortable.update');

Frontend Usage

This package includes a lightweight, native JavaScript drag-and-drop implementation. No external dependencies are required.

  1. Publish the assets. This copies the JS wrapper to your resources folder.

    php artisan vendor:publish --tag=sortable-assets
  2. Import and Start. In your app.js:

    import SortableList from './vendor/sortable/sortable';
    
    SortableList.start();
  3. Add data-sortable to your list. The library will automatically find lists with this attribute.

    • data-sortable: Marks the container.
    • data-sortable-update-url: The endpoint to hit when dropped.
    • .drag: (Optional) Use this class on an element to make it the drag handle.
    <ul data-sortable>
        @foreach($posts as $post)
            <li data-sortable-update-url="{{ route('sortable.update', ['model' => 'Post', 'id' => $post->id]) }}">
                <span class="drag">:::</span>
                {{ $post->title }}
            </li>
        @endforeach
    </ul>

    Note: Ensure you have the <meta name="csrf-token"> tag in your layout head so requests don't fail.

Configuration (Optional)

You can publish the config file to register model aliases (useful if you don't want to expose full class names in URLs).

php artisan vendor:publish --tag=sortable-config

Then in config/sortable.php:

'models' => [
    'posts' => \App\Models\Post::class,
],

Now your route can be /sortable/posts/1 instead of /sortable/Post/1.

Security

By default, only users where $user->isAdmin() returns true can resort items. You can override this in your model:

public function canBePositionedBy($user): bool
{
    return $user->id === $this->user_id;
}