davidgut/sortable
最新稳定版本:v2.0.0
Composer 安装命令:
composer require davidgut/sortable
包简介
A sortable trait for Laravel models
README 文档
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; }
统计信息
- 总下载量: 1
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1
- 点击次数: 0
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-12-15