Search by

kyslik / column-sortable

Kyslik

Package for handling column sorting in Laravel 11-13

Package info

github.com/Kyslik/column-sortable

Type:package

pkg:composer/kyslik/column-sortable

Statistics

Installs: 6 789 971

Dependents: 23

Suggesters: 0

Stars: 643

Open Issues: 1


README

Latest Version Software License Total Downloads Tests

Package for handling column sorting in Laravel 11, 12 and 13. On older Laravel versions:

  • Laravel 5.8-10: Composer installs 8.0.x, the last release that allows them.
  • Laravel 5.4-5.7: use the release whose major and minor version match Laravel's, for example 5.4.* on Laravel 5.4.
  • Laravel 5.1-5.3: checkout branch L5.1-3.

Setup

Composer

Pull this package in through Composer:

{
    "require": {
        "kyslik/column-sortable": "^8.1"
    }
}
composer update

Auto discovery

Simply install the package and let Laravel do its magic.

Manual registration

Only needed if your app turns off package discovery for this package ("dont-discover" in your composer.json). Add the service provider to bootstrap/providers.php:

<?php

use App\Providers\AppServiceProvider;

return [
    AppServiceProvider::class,
    Kyslik\ColumnSortable\ColumnSortableServiceProvider::class,
];

Without the provider, pages that sort fail with Method Illuminate\Http\Request::allFilled does not exist.

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) yourself and make adjustments as you wish.

Usage

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

Note

Schema::hasColumn() is run only when $sortable is not defined - less DB hits per request.

use Illuminate\Foundation\Auth\User as Authenticatable;
use Kyslik\ColumnSortable\Sortable;

class User extends Authenticatable
{
    use 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

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. If that URL already has a query string, the sort parameters are added with &. A #fragment in it stays at the end of the link, after the query string. 'href' => '#users' keeps the current page and jumps to the #users anchor.

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

The links also keep the current request's query string (without sort, direction and page). When the current query string and the 3rd parameter share a key, the current value wins by default, so the 3rd parameter only adds keys that are missing. Set 'override_query_string' => true in the config file to let the 3rd parameter win instead. Then a null value drops that key from the link. That lets you keep two sortable tables (tabs) on one page:

{{-- on /users?tab=users with 'override_query_string' => true --}}
@sortablelink('name', 'Name', ['tab' => 'users'])    {{-- ?tab=users&sort=name&direction=asc --}}
@sortablelink('total', 'Total', ['tab' => 'orders']) {{-- ?tab=orders&sort=total&direction=asc --}}

A link toggles between asc and desc on every click. Put 'direction' => 'asc' or 'direction' => 'desc' in the 3rd parameter to make it always sort in that direction instead, for example in a sort menu. Any other value is ignored and the link toggles as usual. The icon and the anchor classes still show how the column is sorted now, not where the link goes:

@sortablelink('tag', 'A-Z', ['direction' => 'asc'])
@sortablelink('tag', 'Z-A', ['direction' => 'desc'])

default_direction_unsorted sets the first-click direction for all columns. To set it for one column, fix the direction only while that column is not sorted yet. Later clicks toggle as usual:

@sortablelink('created_at', 'Date', request('sort') === 'created_at' ? [] : ['direction' => 'desc'])

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.

Sort URL only

@sortableurl() prints just the URL a @sortablelink would link to, without the <a> tag, for example for a <select> or for JavaScript:

@sortableurl('column', ['parameter' => 'smile'], route('my.custom.route'))

Column (1st) parameter is the same as in @sortablelink. The array() parameter (2nd) is the same as its 3rd parameter, including a fixed direction. The 3rd parameter is an optional custom URL, like the 'href' attribute of @sortablelink. You can omit the 2nd and 3rd parameter. The URL is HTML-escaped, so it can go straight into an attribute:

<select onchange="location = this.value">
    <option value="@sortableurl('name', ['direction' => 'asc'])">Name A-Z</option>
    <option value="@sortableurl('name', ['direction' => 'desc'])">Name Z-A</option>
</select>

In PHP, \Kyslik\ColumnSortable\SortableLink::url(['name', ['direction' => 'desc']]) returns the same URL, not escaped.

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' => [
    'alpha'   => [
        'rows'  => ['description', 'email', 'name', 'slug'],
        'class' => 'fa fa-sort-alpha',
    ],
    'amount'  => [
        'rows'  => ['amount', 'price'],
        'class' => 'fa fa-sort-amount',
    ],
    'numeric' => [
        'rows'  => ['created_at', 'updated_at', 'level', 'id', 'phone_number'],
        'class' => 'fa fa-sort-numeric',
    ],
],

Rest of the config file should be crystal clear and I advise you to skim it.

Font Awesome (default font classes)

The default classes are Font Awesome 4 icons: search "sort" there to see the 12 icons used.

Font Awesome 5

Change the suffix class in the config file 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.

Other icon sets

Font Awesome 6 renamed several sort icons, and other sets such as Bootstrap Icons use their own names. Set sortable_icon (unsorted column), default_icon_set and the columns classes (sorted column), and asc_suffix / desc_suffix (appended to the sorted column's class) in the config file to match your icon set.

Full Example

You may be interested in working example repository, where package usage is demonstrated.

Routes

Route::get('users', [UserController::class, 'index'])->name('users.index');

Controller's 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 (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)

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

@foreach ($users as $user)
    {{ $user->name }}
@endforeach
{{ $users->withQueryString()->links() }}

Note

Blade doesn't recognize a directive right after a letter, digit or underscore: Sort@sortablelink('name') stays as text. After a space or a tag it works: <th>@sortablelink('name')</th>.

HasOne / BelongsTo / MorphOne Relation sorting

Define hasOne relation

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

use Illuminate\Database\Eloquent\Relations\HasOne;

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

The return type (or a @return HasOne docblock) tells the package that detail is a relation, see Which methods count as relations.

Define belongsTo relation

Note

in case there is a self-referencing model (like comments, categories etc.); the joined copy of the table is aliased as sortable_<table> and the listed table keeps its name, so your own where('<table>.<column>', ...) clauses and scopes such as SoftDeletes still filter the listed rows (a {column}Sortable hook on such a relation orders by sortable_<table>.<column>), for more information see issue #60.

use Illuminate\Database\Eloquent\Relations\BelongsTo;

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

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

Define morphOne relation

A polymorphic morphOne() relation works the same way:

use Illuminate\Database\Eloquent\Relations\MorphOne;

/**
 * Get the user's image.
 */
public function image(): MorphOne
{
    return $this->morphOne(Image::class, 'imageable');
}

?sort=image.src joins only the images whose imageable_type is this model's morph class (its morph map alias if it has one), so images of other models with the same id are left out. HasMany, MorphMany and MorphTo relations can't be sorted by.

Define $sortable arrays

Define $sortable array in both models (else, package uses Schema::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

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' => '.'

Which methods count as relations

The relation name in ?sort=relation.column comes from the request, and Eloquent resolves a relation by calling the model method of that name. So the package checks the name before anything is called, and never calls a method to find out whether it is a relation.

If your model defines $sortableRelations, only the names listed there are accepted:

public $sortableRelations = ['detail', 'user'];

Otherwise a name is accepted only when it is a method declared on your model (not by Laravel itself), public, not static, without required parameters, and one of these is true:

  • it has a native return type that is an Eloquent relation, e.g. : HasOne, : ?BelongsTo, : HasOne|BelongsTo;
  • it has no return type, and its @return docblock is a relation: @return \Illuminate\Database\Eloquent\Relations\HasOne, @return HasOne, @return BelongsTo<User, $this>, @return HasOne|null (short names mean classes in Illuminate\Database\Eloquent\Relations);
  • it has neither, and its first statement is return $this->hasOne(...) / return $this->belongsTo(...) (or another relation builder). The package reads the method's source to check this; it does not execute it.

Anything else, for example a relation that builds the relation in a variable first, a dynamic relation registered with resolveRelationUsing(), or a relation inherited from a Laravel trait, throws ColumnSortableException with code 1. Add a return type, or list the relation in $sortableRelations.

The {column}Sortable hook must be a public method of the model. Methods of the Sortable trait itself never count as hooks, also not under an alias, and a column named scope never triggers the hook, because that would call scopeSortable() again.

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. Another example on how to use overriding is issue #41.

Aliasing

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

In model (the property must be public, so the package can also read it on a related model)

...
public $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 for more information on aliasing.

Using withCount()

Aliasing lets you sort by a withCount() column. In the model:

public $sortableAs = ['posts_count'];

In the controller:

$users = $user->withCount('posts')->sortable()->paginate(10);

In the view:

@sortablelink('posts_count', 'Posts')

Sorting by a relation column (for example detail.phone_number) keeps the posts_count column too. See issue #49 for more information.

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 the relation name is not accepted: it does not exist, is not declared in the model, or does not count as a relation (see Which methods count as relations).

Code 2 means that the relation is neither HasOne nor BelongsTo (for example HasMany), so it can't be joined for sorting.

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 any of the codes above, for example ?sort=detail..phone_number (code 0) or ?sort=nope.column (code 1).