laravel-sortablev2 maintained by hippieua
Description
Trait to sort order in Laravel model
Author
Last update
2024/06/13 21:12
(dev-main)
License
Downloads
14
Tags
Laravel Sortable v2
Laravel Sortable v2 is a Laravel package designed to easily add sortable behavior to Eloquent models. This package allows you to manage the order of database records via simple trait inclusion.
Features
- Sortable Trait: Include a trait in your Eloquent models to enable sortable functionality.
- Automatic Order Management: Automatically manages the order field during creation and provides methods to move records up or down.
- Relation Support: Handles sorting within the context of a parent relationship, ideal for nested resources or grouped items.
Installation
To install the package, run the following command in your Laravel project:
composer require hippieua/laravel-sortablev2
Usage
Setup
- Make migration to add sortable field to your model
php artisan make:migration "Add order_id to Categories"
public function up(): void
{
Schema::table('categories', function (Blueprint $table) {
$table->unsignedBigInteger('order_id')->default(0)->after('id');
});
Category::orderBy('id')->each(fn($category, $index) => $category->update(['order_id' => $index++]));
}
- Include the Trait in Your Model
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Hippieua\Sortable2\Sortable2;
class Chapter extends Model
{
use Sortable2;
}
- Define Sortable Field and Optional Relation
Override methods in your model if you need a custom sortable field or a specific relation for sorting:
protected function getSortableField(): string
{
return 'custom_order_field'; // Default is 'order_id'
}
protected function getSortableRelation(): ?BelongsTo
{
return $this->belongsTo(ParentModel::class); // Default is null
}
Managing Order
- Move an Item Up
$chapter = Chapter::find(1);
$chapter->moveUp();
- Move an Item Down
$chapter = Chapter::find(1);
$chapter->moveDown();
Events
The package hooks into several Eloquent model events to ensure data integrity:
creatingsavingupdatingdeletingretrieved- Conditionally
restoringif SoftDeletes is used.
Requirements
- PHP >= 8.0
- Laravel 9.x to 11.x
Contributing
Contributions are welcome, and any issues or pull requests should be submitted on the GitHub repository.
License
The Laravel Sortable v2 package is open-sourced software licensed under the MIT license.