{"id":19311900,"url":"https://github.com/kyslik/column-sortable","last_synced_at":"2025-05-13T23:03:59.292Z","repository":{"id":28017998,"uuid":"31512912","full_name":"Kyslik/column-sortable","owner":"Kyslik","description":"Package for handling column sorting in Laravel 5/6/7/8","archived":false,"fork":false,"pushed_at":"2025-02-24T14:14:37.000Z","size":277,"stargazers_count":648,"open_issues_count":39,"forks_count":110,"subscribers_count":16,"default_branch":"master","last_synced_at":"2025-05-08T15:42:48.630Z","etag":null,"topics":["column-sorting","laravel","laravel-5-package","php","relation-sorting","sorting"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Kyslik.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2015-03-01T22:13:59.000Z","updated_at":"2025-04-19T16:31:50.000Z","dependencies_parsed_at":"2022-07-08T10:51:51.055Z","dependency_job_id":"a109d445-9b97-4f68-a5e7-63ef5a3889db","html_url":"https://github.com/Kyslik/column-sortable","commit_stats":{"total_commits":257,"total_committers":25,"mean_commits":10.28,"dds":"0.22957198443579763","last_synced_commit":"80a7f053cf8e457be06d5fe59371f1b2b5cd8d03"},"previous_names":[],"tags_count":91,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Kyslik%2Fcolumn-sortable","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Kyslik%2Fcolumn-sortable/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Kyslik%2Fcolumn-sortable/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Kyslik%2Fcolumn-sortable/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Kyslik","download_url":"https://codeload.github.com/Kyslik/column-sortable/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254040424,"owners_count":22004536,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["column-sorting","laravel","laravel-5-package","php","relation-sorting","sorting"],"created_at":"2024-11-10T00:31:13.059Z","updated_at":"2025-05-13T23:03:59.274Z","avatar_url":"https://github.com/Kyslik.png","language":"PHP","readme":"# Column sorting for Laravel 5.5-8\n\n[![Latest Version](https://img.shields.io/github/release/Kyslik/column-sortable.svg?style=flat-square)](https://github.com/Kyslik/column-sortable/releases)\n[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md)\n[![Total Downloads](https://img.shields.io/packagist/dt/Kyslik/column-sortable.svg?style=flat-square)](https://packagist.org/packages/Kyslik/column-sortable)\n![run-tests](https://github.com/Kyslik/column-sortable/workflows/run-tests/badge.svg)\n\nPackage 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)\n\n\u003c!-- START doctoc generated TOC please keep comment here to allow auto update --\u003e\n\u003c!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --\u003e\n\n\n- [Column sorting for Laravel 5.5-10](#column-sorting-for-laravel-55-8)\n- [Setup](#setup)\n  - [Composer](#composer)\n    - [Laravel's \u003e=5.5 auto discovery](#laravels-55-auto-discovery)\n    - [Manual installation (pre 5.5)](#manual-installation-pre-55)\n  - [Publish configuration](#publish-configuration)\n- [Usage](#usage)\n  - [Blade Extension](#blade-extension)\n  - [Configuration in few words](#configuration-in-few-words)\n  - [Font Awesome (default font classes)](#font-awesome-default-font-classes)\n    - [Font Awesome 5](#font-awesome-5)\n  - [Full Example](#full-example)\n    - [Routes](#routes)\n    - [Controller's `index()` method](#controllers-index-method)\n    - [View (_pagination included_)](#view-pagination-included)\n- [HasOne / BelongsTo Relation sorting](#hasone--belongsto-relation-sorting)\n  - [Define hasOne relation](#define-hasone-relation)\n  - [Define belongsTo relation](#define-belongsto-relation)\n  - [Define `$sortable` arrays](#define-sortable-arrays)\n  - [Blade and relation sorting](#blade-and-relation-sorting)\n- [ColumnSortable overriding (advanced)](#columnsortable-overriding-advanced)\n- [Aliasing](#aliasing)\n  - [Using `withCount()`](#using-withcount)\n- [Exception to catch](#exception-to-catch)\n\n\u003c!-- END doctoc generated TOC please keep comment here to allow auto update --\u003e\n\n# Setup\n\n## Composer\n\nPull this package in through Composer (development/latest version `dev-master`)\n\n```json\n{\n    \"require\": {\n        \"kyslik/column-sortable\": \"^6.0\"\n    }\n}\n```\n\n```sh\ncomposer update\n```\n\n### Laravel's \u003e=5.5 auto discovery\n\nSimply install the package and let Laravel do its magic.\n\n\u003e [!NOTE]\n\u003e (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.*`.\n\n### Manual installation (pre 5.5)\n\nAdd the service provider to array of providers in `config/app.php`\n\n```php\n'providers' =\u003e [\n\n    App\\Providers\\RouteServiceProvider::class,\n\n    /*\n     * Third Party Service Providers...\n     */\n    Kyslik\\ColumnSortable\\ColumnSortableServiceProvider::class,\n],\n```\n\n## Publish configuration\n\nPublish the package configuration file to your application.\n\n```sh\nphp artisan vendor:publish --provider=\"Kyslik\\ColumnSortable\\ColumnSortableServiceProvider\" --tag=\"config\"\n```\n\nSee configuration file [(`config/columnsortable.php`)](https://github.com/Kyslik/column-sortable/blob/master/src/config/columnsortable.php) yourself and make adjustments as you wish.\n\n# Usage\n\nUse **Sortable** trait inside your *Eloquent* model(s). Define `$sortable` array (see example code below).\n\n\u003e [!NOTE]\n\u003e `Scheme::hasColumn()` is run only when `$sortable` is not defined - less DB hits per request.\n\n```php\nuse Kyslik\\ColumnSortable\\Sortable;\n\nclass User extends Model implements AuthenticatableContract, CanResetPasswordContract\n{\n    use Authenticatable, CanResetPassword, Sortable;\n    ...\n\n    public $sortable = ['id',\n                        'name',\n                        'email',\n                        'created_at',\n                        'updated_at'];\n    ...\n}\n```\n\nYou're set to go.\n\n**Sortable** trait adds Sortable scope to the models so you can use it with paginate.\n\n## Blade Extension\n\nThere is a blade extension for you to use **@sortablelink()**\n\n```blade\n@sortablelink('column', 'Title', ['parameter' =\u003e 'smile'],  ['rel' =\u003e 'nofollow'])\n```\n\n**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.\n\nYou can omit 2nd, 3rd and 4th parameter.\n\nPossible examples and usages of blade extension:\n\n```blade\n@sortablelink('name')\n@sortablelink('name', 'Username')\n@sortablelink('address', trans('fields.address'), ['filter' =\u003e 'active, visible'])\n@sortablelink('address', trans('fields.address'), ['filter' =\u003e 'active, visible'], ['class' =\u003e 'btn btn-block', 'rel' =\u003e 'nofollow', 'href' =\u003e route('my.custom.route')])\n```\n\nIf you do not fill **Title** (2nd parameter) column name is used instead.\n\n\u003e [!NOTE]\n\u003e 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).\n\n## Configuration in few words\n\n**Sortablelink** blade extension distinguishes between *types* (**numeric**, **amount** and **alpha**) and applies different class for each of them.  \n\nSee following snippet:\n\n```php\n'columns' =\u003e [\n    'numeric'  =\u003e [\n        'rows' =\u003e ['created_at', 'updated_at', 'level', 'id'],\n        'class' =\u003e 'fa fa-sort-numeric'\n    ],\n    'amount'   =\u003e [\n        'rows' =\u003e ['price'],\n        'class' =\u003e 'fa fa-sort-amount'\n    ],\n    'alpha'    =\u003e [\n        'rows' =\u003e ['name', 'description', 'email', 'slug'],\n        'class' =\u003e 'fa fa-sort-alpha',\n    ],\n],\n```\n\nRest 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.\n\n## Font Awesome (default font classes)\n\nInstall [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.\n\n### Font Awesome 5\n\nChange 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.\n\n ```php\n/* this is FA 5 compatible.\nsuffix class that is appended when ascending direction is applied */\n'asc_suffix'                    =\u003e '-up',\n\n/* suffix class that is appended when descending direction is applied */\n'desc_suffix'                   =\u003e '-down',\n```\n\n\u003e [!NOTE]\n\u003e If you haven't published the config yet, follow the [instructions above](#publish-configuration).\n\n## Full Example\n\nYou may be interested in [working example repository](https://github.com/Kyslik/column-sortable-example), where package usage is demonstrated.\n\n### Routes\n\n```php\nRoute::get('users', ['as' =\u003e 'users.index', 'uses' =\u003e 'HomeController@index']);\n```\n\n### Controller's `index()` method\n\n```php\npublic function index(User $user)\n{\n    $users = $user-\u003esortable()-\u003epaginate(10);\n\n    return view('user.index')-\u003ewithUsers($users);\n}\n```\n\nYou can set default sorting parameters which will be applied when URL is empty.\n\n\u003e**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)\n\n```php\n$users = $user-\u003esortable('name')-\u003epaginate(10);\n// produces -\u003eorderBy('users.name', 'asc')\n\n$users = $user-\u003esortable(['name'])-\u003epaginate(10); \n// produces -\u003eorderBy('users.name', 'asc')\n\n$users = $user-\u003esortable(['name' =\u003e 'desc'])-\u003epaginate(10);\n// produces -\u003eorderBy('users.name', 'desc')\n```\n\n### View (_pagination included_)\n\n```blade\n@sortablelink('id', 'Id')\n@sortablelink('name')\n\n@foreach ($users as $user)\n    {{ $user-\u003ename }}\n@endforeach\n{!! $users-\u003eappends(\\Request::except('page'))-\u003erender() !!}\n```\n\n\u003e [!NOTE]\n\u003e Blade's ability to recognize directives depends on having space before directive itself `\u003ctr\u003e @sortablelink('Name')`\n\n# HasOne / BelongsTo Relation sorting\n\n## Define hasOne relation\n\nIn order to make relation sorting work, you have to define **hasOne()** relation in your model.\n\n```php\n/**\n * Get the user_detail record associated with the user.\n */\npublic function detail()\n{\n    return $this-\u003ehasOne(App\\UserDetail::class);\n}\n```\n\n## Define belongsTo relation\n\n\u003e [!NOTE]\n\u003e 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).\n\n```php\n/**\n * Get the user that owns the phone.\n */\npublic function user()\n{\n    return $this-\u003ebelongsTo(App\\User::class);\n}\n```\n\nIn *User* model we define **hasOne** relation to *UserDetail* model (which holds phone number and address details).\n\n## Define `$sortable` arrays\n\nDefine `$sortable` array in both models (else, package uses `Scheme::hasColumn()` which is an extra database query).\n\nfor *User*\n\n```php\npublic $sortable = ['id', 'name', 'email', 'created_at', 'updated_at'];\n```\n\nfor *UserDetail*\n\n```php\npublic $sortable = ['address', 'phone_number'];\n```\n\n## Blade and relation sorting\n\nIn order to tell package to sort using relation:\n\n```blade\n@sortablelink('detail.phone_number', 'phone')\n@sortablelink('user.name', 'name')\n```\n\n\u003e [!NOTE]\n\u003e package works with relation \"name\" (method) that you define in model instead of table name.\n\n\u003e [!WARNING]\n\u003e do not use combination of two different relations at the same time, you are going to get errors that relation is not defined\n\nIn config file you can set your own separator in case `.` (dot) is not what you want.\n\n```php\n'uri_relation_column_separator' =\u003e '.'\n```\n\n# ColumnSortable overriding (advanced)\n\nIt is possible to override ColumnSortable relation feature, basically you can write your own join(s) / queries and apply `orderBy()` manually.\n\nSee example:\n\n```php\nclass User extends Model\n{\n    use Sortable;\n\n    public $sortable = ['name'];\n    ...\n\n    public function addressSortable($query, $direction)\n    {\n        return $query-\u003ejoin('user_details', 'users.id', '=', 'user_details.user_id')\n                    -\u003eorderBy('address', $direction)\n                    -\u003eselect('users.*');\n    }\n    ...\n```\n\nController is the same `$users = $user-\u003esortable()-\u003epaginate(10);`\n\nIn view just use `@sortablelink('address')`\n\n\u003e 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).\n\n# Aliasing\n\nIt is possible to declare `$sortableAs` array and use it to alias (bypass column exists check), and ignore prefixing with table.\n\nIn model\n\n```php\n...\n$sortableAs = ['nick_name'];\n...\n```\n\nIn controller\n\n```php\n$users = $user-\u003eselect(['name as nick_name'])-\u003esortable(['nick_name'])-\u003epaginate(10);\n```\n\nIn view\n\n```blade\n@sortablelink('nick_name', 'nick')\n```\n\nSee [#44](https://github.com/Kyslik/column-sortable/issues/44) for more information on aliasing.\n\n## Using `withCount()`\n\nAliasing 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.\n\n# Exception to catch\n\nPackage throws custom exception `ColumnSortableException` with three codes (0, 1, 2).\n\nCode **0** means that `explode()` fails to explode URI parameter \"sort\" in to two values.\nFor example: `sort=detail..phone_number` - produces array with size of 3, which causes package to throw exception with code **0**.\n\nCode **1** means that `$query-\u003egetRelation()` method fails, that means when relation name is invalid (does not exists, is not declared in model).\n\nCode **2** means that provided relation through sort argument is not instance of **hasOne**.\n\nExample how to catch:\n\n```php\n...\ntry {\n    $users = $user-\u003ewith('detail')-\u003esortable(['detail.phone_number'])-\u003epaginate(5);\n} catch (\\Kyslik\\ColumnSortable\\Exceptions\\ColumnSortableException $e) {\n    dd($e);\n}\n```\n\n\u003e [!NOTE]\n\u003e 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`.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkyslik%2Fcolumn-sortable","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkyslik%2Fcolumn-sortable","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkyslik%2Fcolumn-sortable/lists"}