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.0.2(2y ago)15.4k↓50%1MITPHP

Since Oct 11Pushed 5mo agoCompare

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

READMEChangelog (2)DependenciesVersions (3)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).
     *
     * @var array|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:

```
// Example: GET /users?sort=-id
public function index(Request $request)
{
    $sort = $request->input('sort');
    $sortArray = $sort ? explode(',', $sort) : [];

    return User::sort($sortArray)->get();
}

// Supports multiple sort parameters:
// GET /users?sort=name,-id
```

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)
{
    $sort = $request->input('sort');
    $sortArray = is_array($sort) ? $sort : explode(',', $sort);

    return User::sort($sortArray)->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

31

—

LowBetter than 68% of packages

Maintenance47

Moderate activity, may be stable

Popularity25

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity34

Early-stage or recently created project

 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 ~22 days

Total

2

Last Release

928d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/3ef4a79c6f9a9afe04267a19b98fe0a5a45930c92d08fd720b233ab21ae102ca?d=identicon)[sl0wik](/maintainers/sl0wik)

---

Top Contributors

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

---

Tags

laraveltraitsortablefirevel

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

[cybercog/laravel-love

Make Laravel Eloquent models reactable with any type of emotions in a minutes!

1.2k302.7k1](/packages/cybercog-laravel-love)[rutorika/sortable

Adds sortable behavior and ordering to Laravel Eloquent models. Grouping and many to many supported.

299992.5k14](/packages/rutorika-sortable)[rtconner/laravel-likeable

Trait for Laravel Eloquent models to allow easy implementation of a 'like' or 'favorite' or 'remember' feature.

394388.0k5](/packages/rtconner-laravel-likeable)[cybercog/laravel-nova-ban

A Laravel Nova banning functionality for your application.

40199.8k](/packages/cybercog-laravel-nova-ban)[pawelmysior/laravel-publishable

Toggle the published state of your Eloquent models easily

2219.1k3](/packages/pawelmysior-laravel-publishable)

PHPackages © 2026

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