PHPackages                             nelkasovic/column-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. [Utility &amp; Helpers](/categories/utility)
4. /
5. nelkasovic/column-sortable

ActivePackage[Utility &amp; Helpers](/categories/utility)

nelkasovic/column-sortable
==========================

Package for handling column sorting in Laravel 6.x

v1.0.2(3y ago)0383MITPHPPHP ^8.1

Since Feb 16Pushed 3y agoCompare

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

READMEChangelog (2)Dependencies (2)Versions (2)Used By (0)

- [Column sorting for Laravel 5.5-8](#column-sorting-for-laravel-55-8)
- [Setup](#setup)
    - [Composer](#composer)
        - [Laravel's &gt;=5.5 auto discovery](#laravels-55-auto-discovery)
        - [Manual installation (pre 5.5)](#manual-installation-pre-55)
    - [Publish configuration](#publish-configuration)
- [Usage](#usage)
    - [Blade Extension](#blade-extension)
    - [Configuration in few words](#configuration-in-few-words)
    - [Font Awesome (default font classes)](#font-awesome-default-font-classes)
        - [Font Awesome 5](#font-awesome-5)
    - [Full Example](#full-example)
        - [Routes](#routes)
        - [Controller's `index()` method](#controllers-index-method)
        - [View (*pagination included*)](#view-pagination-included)
- [HasOne / BelongsTo Relation sorting](#hasone--belongsto-relation-sorting)
    - [Define hasOne relation](#define-hasone-relation)
    - [Define belongsTo relation](#define-belongsto-relation)
    - [Define `$sortable` arrays](#define-sortable-arrays)
    - [Blade and relation sorting](#blade-and-relation-sorting)
- [ColumnSortable overriding (advanced)](#columnsortable-overriding-advanced)
- [Aliasing](#aliasing)
    - [Using `withCount()`](#using-withcount)
- [Exception to catch](#exception-to-catch)

Column sorting for Laravel 5.5-8
================================

[](#column-sorting-for-laravel-55-8)

[![Latest Version](https://camo.githubusercontent.com/e15cf32b9d6ac5887c9751a4e414340817df61de70f1b72be91f389ff4bfba0a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f4b79736c696b2f636f6c756d6e2d736f727461626c652e7376673f7374796c653d666c61742d737175617265)](https://github.com/Kyslik/column-sortable/releases)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![Total Downloads](https://camo.githubusercontent.com/bf4a1e17d2bb6badb6e4c384e21abd06f0782219daed89d6a2aa86f8c38f964c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f4b79736c696b2f636f6c756d6e2d736f727461626c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/Kyslik/column-sortable)[![run-tests](https://github.com/Kyslik/column-sortable/workflows/run-tests/badge.svg)](https://github.com/Kyslik/column-sortable/workflows/run-tests/badge.svg)

Package for handling column sorting in Laravel 5.\[5-8\]. For earlier versions of Laravel checkout branch [L5.1-3](https://github.com/Kyslik/column-sortable/tree/L5.1-3)

Setup
=====

[](#setup)

Composer
--------

[](#composer)

Pull this package in through Composer (development/latest version `dev-master`)

```
{
    "require": {
        "kyslik/column-sortable": "^6.0"
    }
}
```

```
composer update
```

### Laravel's &gt;=5.5 auto discovery

[](#laravels-55-auto-discovery)

Simply install the package and let Laravel do its magic.

> **Note (pre Laravel 6.0)**: : major and minor versions should match with Laravel's version, for example if you are using Laravel 5.4, column-sortable version should be `5.4.*`.

### Manual installation (pre 5.5)

[](#manual-installation-pre-55)

Add the service provider to array of providers in `config/app.php`

```
'providers' => [

    App\Providers\RouteServiceProvider::class,

    /*
     * Third Party Service Providers...
     */
    Kyslik\ColumnSortable\ColumnSortableServiceProvider::class,
],
```

Publish configuration
---------------------

[](#publish-configuration)

Publish the package configuration file to your application.

```
php artisan vendor:publish --provider="Kyslik\ColumnSortable\ColumnSortableServiceProvider" --tag="config"
```

See configuration file [(`config/columnsortable.php`)](https://github.com/Kyslik/column-sortable/blob/master/src/config/columnsortable.php) yourself and make adjustments as you wish.

Usage
=====

[](#usage)

Use **Sortable** trait inside your *Eloquent* model(s). Define `$sortable` array (see example code below).

> **Note**: `Scheme::hasColumn()` is run only when `$sortable` is not defined - less DB hits per request.

```
use Kyslik\ColumnSortable\Sortable;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
    use Authenticatable, CanResetPassword, Sortable;
    ...

    public $sortable = ['id',
                        'name',
                        'email',
                        'created_at',
                        'updated_at'];
    ...
}
```

You're set to go.

**Sortable** trait adds Sortable scope to the models so you can use it with paginate.

Blade Extension
---------------

[](#blade-extension)

There is a blade extension for you to use **@sortablelink()**

```
@sortablelink('column', 'Title', ['parameter' => 'smile'],  ['rel' => 'nofollow'])
```

**Column** (1st) parameter is column in database, **Title** (2nd) parameter is displayed inside anchor tags, `array()` parameter (3rd) is default (GET) query strings parameter and `array()` parameter (4th) is for additional anchor-tag attributes. You can use a custom URL as 'href' attribute in the 4th parameter, and the query string will be appended to it.

You can omit 2nd, 3rd and 4th parameter.

Possible examples and usages of blade extension:

```
@sortablelink('name')
@sortablelink('name', 'Username')
@sortablelink('address', trans('fields.address'), ['filter' => 'active, visible'])
@sortablelink('address', trans('fields.address'), ['filter' => 'active, visible'], ['class' => 'btn btn-block', 'rel' => 'nofollow', 'href' => route('my.custom.route')])
```

If you do not fill **Title** (2nd parameter) column name is used instead.

> **Note**: you can set default formatting function that is applied on **Title** (2nd parameter), by default this is set to [`ucfirst`](http://php.net/manual/en/function.ucfirst.php).

Configuration in few words
--------------------------

[](#configuration-in-few-words)

**Sortablelink** blade extension distinguishes between *types* (**numeric**, **amount** and **alpha**) and applies different class for each of them.

See following snippet:

```
'columns' => [
    'numeric'  => [
        'rows' => ['created_at', 'updated_at', 'level', 'id'],
        'class' => 'fa fa-sort-numeric'
    ],
    'amount'   => [
        'rows' => ['price'],
        'class' => 'fa fa-sort-amount'
    ],
    'alpha'    => [
        'rows' => ['name', 'description', 'email', 'slug'],
        'class' => 'fa fa-sort-alpha',
    ],
],
```

Rest of the [config file](https://github.com/Kyslik/column-sortable/blob/master/src/config/columnsortable.php) should be crystal clear and I advise you to skim it.

Font Awesome (default font classes)
-----------------------------------

[](#font-awesome-default-font-classes)

Install [Font-Awesome](https://fontawesome.com/v4.7.0/) for visual [Joy](http://pixar.wikia.com/wiki/Joy). Search "sort" in [cheatsheet](https://fontawesome.com/v4.7.0/icons/) and see used icons (12) yourself.

### Font Awesome 5

[](#font-awesome-5)

Change the suffix class in the [config file](https://github.com/Kyslik/column-sortable/blob/master/src/config/columnsortable.php) from `-asc`/`-desc` (FA 4) to `-up`/`-down` (FA 5) respectively.

```
/* this is FA 5 compatible.
suffix class that is appended when ascending direction is applied */
'asc_suffix'                    => '-up',

/* suffix class that is appended when descending direction is applied */
'desc_suffix'                   => '-down',
```

> **Note**: If you haven't published the config yet, follow the [instructions above](#publish-configuration).

Full Example
------------

[](#full-example)

You may be interested in [working example repository](https://github.com/Kyslik/column-sortable-example), where package usage is demonstrated.

### Routes

[](#routes)

```
Route::get('users', ['as' => 'users.index', 'uses' => 'HomeController@index']);
```

### Controller's `index()` method

[](#controllers-index-method)

```
public function index(User $user)
{
    $users = $user->sortable()->paginate(10);

    return view('user.index')->withUsers($users);
}
```

You can set default sorting parameters which will be applied when URL is empty.

> **For example**: page is loaded for first time, default direction is [configurable](https://github.com/Kyslik/column-sortable/blob/master/src/config/columnsortable.php#L103) (asc)

```
$users = $user->sortable('name')->paginate(10);
// produces ->orderBy('users.name', 'asc')

$users = $user->sortable(['name'])->paginate(10);
// produces ->orderBy('users.name', 'asc')

$users = $user->sortable(['name' => 'desc'])->paginate(10);
// produces ->orderBy('users.name', 'desc')
```

### View (*pagination included*)

[](#view-pagination-included)

```
@sortablelink('id', 'Id')
@sortablelink('name')

@foreach ($users as $user)
    {{ $user->name }}
@endforeach
{!! $users->appends(\Request::except('page'))->render() !!}
```

> **Note**: Blade's ability to recognize directives depends on having space before directive itself ` @sortablelink('Name')`

HasOne / BelongsTo Relation sorting
===================================

[](#hasone--belongsto-relation-sorting)

Define hasOne relation
----------------------

[](#define-hasone-relation)

In order to make relation sorting work, you have to define **hasOne()** relation in your model.

```
/**
* Get the user_detail record associated with the user.
*/
public function detail()
{
    return $this->hasOne(App\UserDetail::class);
}
```

Define belongsTo relation
-------------------------

[](#define-belongsto-relation)

> **Note**: in case there is a self-referencing model (like comments, categories etc.); parent table will be aliased with `parent_` string, for more information see [issue #60](https://github.com/Kyslik/column-sortable/issues/60).

```
/**
 * Get the user that owns the phone.
 */
public function user()
{
    return $this->belongsTo(App\User::class);
}
```

In *User* model we define **hasOne** relation to *UserDetail* model (which holds phone number and address details).

Define `$sortable` arrays
-------------------------

[](#define-sortable-arrays)

Define `$sortable` array in both models (else, package uses `Scheme::hasColumn()` which is an extra database query).

for *User*

```
public $sortable = ['id', 'name', 'email', 'created_at', 'updated_at'];
```

for *UserDetail*

```
public $sortable = ['address', 'phone_number'];
```

Blade and relation sorting
--------------------------

[](#blade-and-relation-sorting)

In order to tell package to sort using relation:

```
@sortablelink('detail.phone_number', 'phone')
@sortablelink('user.name', 'name')
```

> **Note**: package works with relation "name" (method) that you define in model instead of table name.

> **WARNING**: do not use combination of two different relations at the same time, you are going to get errors that relation is not defined

In config file you can set your own separator in case `.` (dot) is not what you want.

```
'uri_relation_column_separator' => '.'
```

ColumnSortable overriding (advanced)
====================================

[](#columnsortable-overriding-advanced)

It is possible to override ColumnSortable relation feature, basically you can write your own join(s) / queries and apply `orderBy()` manually.

See example:

```
class User extends Model
{
    use Sortable;

    public $sortable = ['name'];
    ...

    public function addressSortable($query, $direction)
    {
        return $query->join('user_details', 'users.id', '=', 'user_details.user_id')
                    ->orderBy('address', $direction)
                    ->select('users.*');
    }
    ...
```

Controller is the same `$users = $user->sortable()->paginate(10);`

In view just use `@sortablelink('address')`

> Huge thanks to @neutralrockets and his comments on [\#8](https://github.com/Kyslik/column-sortable/issues/8). Another example on how to use overriding is issue [\#41](https://github.com/Kyslik/column-sortable/issues/41#issuecomment-250895909).

Aliasing
========

[](#aliasing)

It is possible to declare `$sortableAs` array and use it to alias (bypass column exists check), and ignore prefixing with table.

In model

```
...
$sortableAs = ['nick_name'];
...
```

In controller

```
$users = $user->select(['name as nick_name'])->sortable(['nick_name'])->paginate(10);
```

In view

```
@sortablelink('nick_name', 'nick')
```

See [\#44](https://github.com/Kyslik/column-sortable/issues/44) for more information on aliasing.

Using `withCount()`
-------------------

[](#using-withcount)

Aliasing is useful when you want to sort results with [`withCount()`](https://laravel.com/docs/5.8/eloquent-relationships#counting-related-models), see [issue #49](https://github.com/Kyslik/column-sortable/issues/49) for more information.

Exception to catch
==================

[](#exception-to-catch)

Package throws custom exception `ColumnSortableException` with three codes (0, 1, 2).

Code 0 means that `explode()` fails to explode URI parameter "sort" in to two values. For example: `sort=detail..phone_number` - produces array with size of 3, which causes package to throw exception with code 0.

Code **1** means that `$query->getRelation()` method fails, that means when relation name is invalid (does not exists, is not declared in model).

Code **2** means that provided relation through sort argument is not instance of **hasOne**.

Example how to catch:

```
...
try {
    $users = $user->with('detail')->sortable(['detail.phone_number'])->paginate(5);
} catch (\Kyslik\ColumnSortable\Exceptions\ColumnSortableException $e) {
    dd($e);
}
```

> **Note**: I strongly recommend to catch **ColumnSortableException** because there is a user input in question (GET parameter) and any user can modify it in such way that package throws ColumnSortableException with code `0`.

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity12

Limited adoption so far

Community17

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 85.6% 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

Unknown

Total

1

Last Release

1177d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/1759407?v=4)[Nermin Elkasovic](/maintainers/nelkasovic)[@nelkasovic](https://github.com/nelkasovic)

---

Top Contributors

[![Kyslik](https://avatars.githubusercontent.com/u/2067589?v=4)](https://github.com/Kyslik "Kyslik (243 commits)")[![Healyhatman](https://avatars.githubusercontent.com/u/13272508?v=4)](https://github.com/Healyhatman "Healyhatman (7 commits)")[![timopaul](https://avatars.githubusercontent.com/u/16575322?v=4)](https://github.com/timopaul "timopaul (7 commits)")[![d13r](https://avatars.githubusercontent.com/u/236616?v=4)](https://github.com/d13r "d13r (3 commits)")[![pedro-lucas](https://avatars.githubusercontent.com/u/8092560?v=4)](https://github.com/pedro-lucas "pedro-lucas (3 commits)")[![sjrahimian](https://avatars.githubusercontent.com/u/20866450?v=4)](https://github.com/sjrahimian "sjrahimian (3 commits)")[![olumby](https://avatars.githubusercontent.com/u/5549119?v=4)](https://github.com/olumby "olumby (2 commits)")[![laravel-shift](https://avatars.githubusercontent.com/u/15991828?v=4)](https://github.com/laravel-shift "laravel-shift (2 commits)")[![nelkasovic](https://avatars.githubusercontent.com/u/1759407?v=4)](https://github.com/nelkasovic "nelkasovic (2 commits)")[![tntsoft](https://avatars.githubusercontent.com/u/5844176?v=4)](https://github.com/tntsoft "tntsoft (1 commits)")[![TrieBr](https://avatars.githubusercontent.com/u/348719?v=4)](https://github.com/TrieBr "TrieBr (1 commits)")[![anok](https://avatars.githubusercontent.com/u/54154?v=4)](https://github.com/anok "anok (1 commits)")[![veganista](https://avatars.githubusercontent.com/u/405763?v=4)](https://github.com/veganista "veganista (1 commits)")[![antkowiakit](https://avatars.githubusercontent.com/u/2530655?v=4)](https://github.com/antkowiakit "antkowiakit (1 commits)")[![cinject](https://avatars.githubusercontent.com/u/1239943?v=4)](https://github.com/cinject "cinject (1 commits)")[![ecodrutz](https://avatars.githubusercontent.com/u/24397899?v=4)](https://github.com/ecodrutz "ecodrutz (1 commits)")[![erik-perri](https://avatars.githubusercontent.com/u/46399654?v=4)](https://github.com/erik-perri "erik-perri (1 commits)")[![Jeroen-G](https://avatars.githubusercontent.com/u/1116853?v=4)](https://github.com/Jeroen-G "Jeroen-G (1 commits)")[![justinmoh](https://avatars.githubusercontent.com/u/11174621?v=4)](https://github.com/justinmoh "justinmoh (1 commits)")[![llaski](https://avatars.githubusercontent.com/u/833579?v=4)](https://github.com/llaski "llaski (1 commits)")

---

Tags

laravelsortablesortsortingcolumn

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[kyslik/column-sortable

Package for handling column sorting in Laravel 6.x

6485.6M21](/packages/kyslik-column-sortable)[rutorika/sortable

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

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

Sortable behavior package for Laravel

27175.6k](/packages/akaunting-laravel-sortable)[symbiote/silverstripe-gridfieldextensions

A collection of useful grid field components

971.8M232](/packages/symbiote-silverstripe-gridfieldextensions)[undefinedoffset/sortablegridfield

Adds drag and drop functionality to Silverstripe's GridField

941.2M50](/packages/undefinedoffset-sortablegridfield)[indexzer0/eloquent-filtering

Powerful eloquent filtering

22425.9k3](/packages/indexzer0-eloquent-filtering)

PHPackages © 2026

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