PHPackages                             jedrzej/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. jedrzej/sortable

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

jedrzej/sortable
================

Sortable trait for Laravel's Eloquent models - sort your models using request parameters

0.0.12(6y ago)54261.0k↓35.7%6[1 issues](https://github.com/jedrzej/sortable/issues)1MITPHP

Since Aug 15Pushed 6y ago1 watchersCompare

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

READMEChangelogDependencies (6)Versions (13)Used By (1)

Sortable trait for Laravel's Eloquent models
============================================

[](#sortable-trait-for-laravels-eloquent-models)

This package adds sorting functionality to Eloquent models in Laravel 4/5/6.

You could also find those packages useful:

- [Searchable](https://github.com/jedrzej/searchable) - Allows filtering your models using request parameters
- [Withable](https://github.com/jedrzej/withable) - Allows eager loading of relations using request parameters
- [Pimpable](https://github.com/jedrzej/pimpable) - A meta package that combines Sortable, Searchable and Withable behaviours

Composer install
----------------

[](#composer-install)

Add the following line to `composer.json` file in your project:

```
"jedrzej/sortable": "0.0.12"

```

or run the following in the commandline in your project's root folder:

```
composer require "jedrzej/sortable" "0.0.12"

```

Setting up sortable models
--------------------------

[](#setting-up-sortable-models)

In order to make an Eloquent model sortable, add the trait to the model and define a list of fields that the model can be sorted by. You can either define a `$sortable` property or implement a `getSortableAttributes` method if you want to execute some logic to define list of sortable fields.

```
use Jedrzej\Sortable\SortableTrait;

class Post extends Eloquent
{
    use SortableTrait;

    // either a property holding a list of sortable fields...
    public $sortable = ['title', 'forum_id', 'created_at'];

    // ...or a method that returns a list of sortable fields
    public function getSortableAttributes()
    {
        return ['title', 'forum_id', 'created_at'];
    }
}
```

In order to make all fields sortable put an asterisk `*` in the list of sortable fields:

```
public $sortable = ['*'];
```

Sorting models
--------------

[](#sorting-models)

`SortableTrait` adds a `sorted()` scope to the model - you can pass it a query being an array of sorting conditions:

```
// return all posts sorted by creation date in descending order
Post::sorted('created_at,desc')->get();

// return all users sorted by level in ascending order and then by points indescending orders
User::sorted(['level,asc', 'points,desc'])->get();
```

or it will use `sort` parameter from the request as default:

```
// return all posts sorted by creation date in descending order by appending to URL
?sort=created_at,desc
//and then calling
Post::sorted()->get();

// return all users sorted by level in ascending order and then by points indescending orders by appending to URL
?sort[]=level,asc&sort[]=points,desc
// and then calling
User::sorted()->get();
```

Overwriting default sorting logic
---------------------------------

[](#overwriting-default-sorting-logic)

It is possible to overwrite how sorting parameters are used and applied to the query by implementing a callback in your model named `sortFieldName`, e.g.:

```
// return all posts sorted by creation date in descending order
Post::sorted('created_at,desc')->get();

// in model class overwrite the sorting logic so that 'created' field is used instead of 'created_at'
public function sortCreatedAt($query, $direction = 'desc')
{
    return $query->orderBy('created', $direction);
}
```

Defining default sorting criteria
---------------------------------

[](#defining-default-sorting-criteria)

It is possible to define default sorting criteria that will be used if no sorting criteria are provided in the request or passed to `sorted` method of your model. Default sorting criteria should be defined in $defaultSortCriteria property, e.g.:

```
// sort by latest first
protected $defaultSortCriteria = ['created_at,desc'];
```

Defining default sorting order
------------------------------

[](#defining-default-sorting-order)

By default asc is considered as default sorting order. It is possible to define default sorting order that will be used if no sorting order is provided in the request or passed to `sorted` method of your model. Default sorting order should be defined in $defaultSortOrder property, e.g.:

```
// sort in desc order by default if no order is specified in request
protected $defaultSortOrder = 'desc';
// sort in asc order by default if no order is specified in request
protected $defaultSortOrder = 'asc';
```

Additional configuration
------------------------

[](#additional-configuration)

If you are using `sort` request parameter for other purpose, you can change the name of the parameter that will be interpreted as sorting criteria by setting a `$sortParameterName` property in your model, e.g.:

```
 protected $sortParameterName = 'sortBy';
```

###  Health Score

40

—

FairBetter than 88% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity47

Moderate usage in the ecosystem

Community17

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor1

Top contributor holds 87.5% 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 ~134 days

Recently: every ~331 days

Total

12

Last Release

2448d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e3752b22b5f831cbf76e2d5a77f429e7fde1dfcfafc09d26fc5a950bc22b7880?d=identicon)[jedrzej](/maintainers/jedrzej)

---

Top Contributors

[![jedrzej](https://avatars.githubusercontent.com/u/291904?v=4)](https://github.com/jedrzej "jedrzej (21 commits)")[![gbrock](https://avatars.githubusercontent.com/u/4151394?v=4)](https://github.com/gbrock "gbrock (1 commits)")[![jbrooksuk](https://avatars.githubusercontent.com/u/246103?v=4)](https://github.com/jbrooksuk "jbrooksuk (1 commits)")[![jedrzej-x-team-com](https://avatars.githubusercontent.com/u/120025182?v=4)](https://github.com/jedrzej-x-team-com "jedrzej-x-team-com (1 commits)")

---

Tags

eloquenteloquent-modelslaravelphpsortsort-criteriasortable-modelssortingrequestapilaravelmodeleloquentsortablesort

###  Code Quality

TestsCodeception

### Embed Badge

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

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

###  Alternatives

[spatie/eloquent-sortable

Sortable behaviour for eloquent models

1.5k22.9M268](/packages/spatie-eloquent-sortable)[jedrzej/pimpable

Laravel 4/5/6 package that allows to dynamically filter, sort and eager load relations for your models using request parameters

105179.0k1](/packages/jedrzej-pimpable)[dyrynda/laravel-model-uuid

This package allows you to easily work with UUIDs in your Laravel models.

4802.8M8](/packages/dyrynda-laravel-model-uuid)[jedrzej/searchable

Searchable trait for Laravel's Eloquent models - filter your models using request parameters

127259.1k5](/packages/jedrzej-searchable)[spiritix/lada-cache

A Redis based, automated and scalable database caching layer for Laravel

591444.8k2](/packages/spiritix-lada-cache)[sebastiaanluca/laravel-boolean-dates

Automatically convert Eloquent model boolean attributes to dates (and back).

40111.7k1](/packages/sebastiaanluca-laravel-boolean-dates)

PHPackages © 2026

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