PHPackages                             firevel/sortable - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. firevel/sortable

ActiveLibrary[Database &amp; ORM](/categories/database)

firevel/sortable
================

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

0.1.0(1mo ago)16.3k↓61%1MITPHPPHP ^8.2CI passing

Since Oct 11Pushed 1mo agoCompare

[ Source](https://github.com/firevel/sortable)[ Packagist](https://packagist.org/packages/firevel/sortable)[ RSS](/packages/firevel-sortable/feed)WikiDiscussions main Synced 3d ago

READMEChangelog (4)Dependencies (5)Versions (5)Used By (1)

Laravel Sortable
================

[](#laravel-sortable)

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
------------

[](#installation)

Using Composer:

```
composer require firevel/sortable
```

Setup
-----

[](#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:
--------

[](#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
-----

[](#usage)

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

### Ascending Order:

[](#ascending-order)

To sort by `name` in ascending order:

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

### Descending Order:

[](#descending-order)

To sort by `id` in descending order:

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

The `-` sign before the field name indicates descending order.

### Multiple Columns:

[](#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:

[](#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
-------------------

[](#additional-features)

### Default Sorting

[](#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

[](#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

[](#validation-rule-for-form-requests)

The package provides two ways to validate sort parameters:

#### String-based validation:

[](#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):

[](#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

###  Health Score

46

—

FairBetter than 92% of packages

Maintenance91

Actively maintained with recent releases

Popularity25

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~319 days

Total

4

Last Release

41d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/2696038?v=4)[Michael Slowik](/maintainers/sl0wik)[@sl0wik](https://github.com/sl0wik)

---

Top Contributors

[![sl0wik](https://avatars.githubusercontent.com/u/2696038?v=4)](https://github.com/sl0wik "sl0wik (15 commits)")

---

Tags

laraveltraitsortablefirevel

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/firevel-sortable/health.svg)

```
[![Health](https://phpackages.com/badges/firevel-sortable/health.svg)](https://phpackages.com/packages/firevel-sortable)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M346](/packages/psalm-plugin-laravel)[laravel/ai

The official AI SDK for Laravel.

1.0k3.2M200](/packages/laravel-ai)[illuminate/database

The Illuminate Database package.

2.8k54.9M11.7k](/packages/illuminate-database)[api-platform/laravel

API Platform support for Laravel

58171.6k14](/packages/api-platform-laravel)[yajra/laravel-oci8

Oracle DB driver for Laravel via OCI8

8793.2M25](/packages/yajra-laravel-oci8)[illuminate/queue

The Illuminate Queue package.

21332.6M1.6k](/packages/illuminate-queue)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
