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
Requires
- php: ^8.2
- illuminate/support: ^11.0|^12.0
Requires (Dev)
- orchestra/testbench: ^9.0|^10.0
- pestphp/pest: ^3.0
- pestphp/pest-plugin-laravel: ^3.0
README
Simple drag-and-drop sorting for your Laravel models.
Installation
composer require davidgut/sortable
Setup
-
Add the column to your table. By default, the package looks for a
positioncolumn.Schema::create('posts', function (Blueprint $table) { // ... $table->integer('position')->nullable(); });
-
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 }
-
Add the API Route. Add the following to your
routes/web.phporroutes/api.phpto 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.
-
Publish the assets. This copies the JS wrapper to your resources folder.
php artisan vendor:publish --tag=sortable-assets
-
Import and Start. In your
app.js:import SortableList from './vendor/sortable/sortable'; SortableList.start();
-
Add
data-sortableto 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; }