承接 firevel/sortable 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

firevel/sortable

Composer 安装命令:

composer require firevel/sortable

包简介

A simple trait to make your Laravel Eloquent models sortable with ease.

README 文档

README

A simple trait to make your Laravel Eloquent models sortable with ease. Designed for API usage where you can pass sort parameters directly from query strings (e.g., /users?sort=-id).

Installation

Using Composer:

composer require firevel/sortable

Setup

  1. Import the Sortable trait in your Eloquent model.

  2. Add a protected $sortable array property to your model. This array should list the fields you want to allow for sorting.

Example:

use Firevel\Sortable\Sortable;

class User extends Model {
    use Sortable;

    /**
     * Fields allowed for sorting.
     *
     * @var array
     */
    protected $sortable = ['id', 'name', 'email'];

    /**
     * Default sorting when no sort parameter is provided (optional).
     * May be an array (['-id']) or a string ('-id').
     *
     * @var array|string|null
     */
    protected $defaultSort = ['-id'];
}

Usage

You can now easily sort your models using the sort() query scope.

Ascending Order:

To sort by name in ascending order:

User::sort(['name'])->get();

Descending Order:

To sort by id in descending order:

User::sort(['-id'])->get();

The - sign before the field name indicates descending order.

Multiple Columns:

You can sort by multiple columns at once. The sorting is applied in the order specified:

User::sort(['name', '-id'])->get();

This will sort by name ascending, then by id descending.

API Usage:

This trait is particularly useful for API endpoints where you receive sort parameters from query strings. You can pass the raw JSON:API style string straight to sort() — no need to explode it yourself:

// Example: GET /users?sort=name,-id
public function index(Request $request)
{
    return User::sort($request->input('sort'))->get();
}

sort() accepts either a comma-separated string ("name,-id") or an array (['name', '-id']), so both of these are equivalent:

User::sort('name,-id')->get();
User::sort(['name', '-id'])->get();

Whitespace around fields is trimmed, so "name, -id" works too.

Note: sort() only applies fields listed in the model's $sortable allowlist. Any field that isn't allowed is silently ignored rather than raising an error — so an untrusted ?sort= value can never order by an unexpected column. If no valid fields remain, the model's $defaultSort (if any) is applied. To reject invalid input with a validation error instead, use the validation rule below.

Additional Features

Default Sorting

You can define a default sort order that will be applied when no sort parameters are provided:

class User extends Model {
    use Sortable;

    protected $sortable = ['id', 'name', 'email', 'created_at'];
    protected $defaultSort = ['-created_at'];  // Sort by newest first by default
}

// When called with no parameters, uses default sort
User::sort([])->get();  // Returns users sorted by created_at DESC

Check if Field is Sortable

You can check if a specific field is sortable using the isSortable() method:

$user = new User();

if ($user->isSortable('name')) {
    // Field is sortable
}

if ($user->isSortable('-id')) {
    // Also works with descending prefix
}

Validation Rule for Form Requests

The package provides two ways to validate sort parameters:

String-based validation:

class ListUsersRequest extends FormRequest
{
    public function rules()
    {
        return [
            'sort' => ['nullable', 'string', 'sort_fields:App\Models\User'],
        ];
    }
}

Object-based validation (provides more detailed error messages):

use Firevel\Sortable\SortField;
use App\Models\User;

class ListUsersRequest extends FormRequest
{
    public function rules()
    {
        return [
            'sort' => ['nullable', 'string', new SortField(User::class)],
        ];
    }
}

Both approaches work with string and array inputs:

// String input (e.g., from query string ?sort=name,-id)
'sort' => ['nullable', 'string', 'sort_fields:App\Models\User']

// Array input
'sort' => ['nullable', 'array', 'sort_fields:App\Models\User']

Example usage in a controller:

public function index(ListUsersRequest $request)
{
    return User::sort($request->input('sort'))->get();
}

The validation rule will automatically:

  • Check if each field is in the model's $sortable array
  • Handle both ascending (name) and descending (-name) formats
  • Provide clear error messages for invalid fields

firevel/sortable 适用场景与选型建议

firevel/sortable 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 6.25k 次下载、GitHub Stars 达 1, 最近一次更新时间为 2023 年 10 月 11 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「sortable」 「trait」 「laravel」 「firevel」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 firevel/sortable 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 firevel/sortable 我们能提供哪些服务?
定制开发 / 二次开发

基于 firevel/sortable 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 6.25k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 32
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2023-10-11