All Projects → Kyslik → Column Sortable

Kyslik / Column Sortable

Licence: mit
Package for handling column sorting in Laravel 5/6/7/8

Projects that are alternatives of or similar to Column Sortable

Laravel Masterpass
Helps you securely setup a master password and login into user accounts with it.
Stars: ✭ 289 (-41.73%)
Mutual labels:  laravel, laravel-5-package
Jwt Auth Guard
JWT Auth Guard for Laravel and Lumen Frameworks.
Stars: ✭ 319 (-35.69%)
Mutual labels:  laravel, laravel-5-package
Administrator
a fork from Frozennode/Administrator
Stars: ✭ 296 (-40.32%)
Mutual labels:  laravel, laravel-5-package
Laravel Gamp
📊 Laravel Google Analytics Measurement Protocol Package
Stars: ✭ 271 (-45.36%)
Mutual labels:  laravel, laravel-5-package
Lada Cache
A Redis based, fully automated and scalable database cache layer for Laravel
Stars: ✭ 424 (-14.52%)
Mutual labels:  laravel, laravel-5-package
Laravel Chunk Upload
The basic implementation for chunk upload with multiple providers support like jQuery-file-upload, pupload, DropZone and resumable.js
Stars: ✭ 275 (-44.56%)
Mutual labels:  laravel, laravel-5-package
Laravel Log Enhancer
Make debugging easier by adding more data to your laravel logs (Laravel 5.6+)
Stars: ✭ 311 (-37.3%)
Mutual labels:  laravel, laravel-5-package
Laracrud
Laravel Code Generator based on MySQL Database
Stars: ✭ 238 (-52.02%)
Mutual labels:  laravel, laravel-5-package
Laravel Server Monitor
Server Monitoring Command for Laravel Applications
Stars: ✭ 424 (-14.52%)
Mutual labels:  laravel, laravel-5-package
Laravel Translation
Translation management for your Laravel application.
Stars: ✭ 350 (-29.44%)
Mutual labels:  laravel, laravel-5-package
Laravel Gitscrum
GitScrum is a Project Management Tool, developed to help entrepreneurs, freelancers, managers, and teams Skyrocket their Productivity with the Agile methodology and Gamification.
Stars: ✭ 2,686 (+441.53%)
Mutual labels:  laravel, laravel-5-package
Laravel Js Localization
🌐 Convert your Laravel messages and consume them in the front-end!
Stars: ✭ 451 (-9.07%)
Mutual labels:  laravel, laravel-5-package
Bouncer
Eloquent roles and abilities.
Stars: ✭ 2,763 (+457.06%)
Mutual labels:  laravel, laravel-5-package
Laravel Achievements
Achievements for Laravel 5.3+
Stars: ✭ 279 (-43.75%)
Mutual labels:  laravel, laravel-5-package
Rutorika Sortable
Adds sortable behavior to Laravel Eloquent models
Stars: ✭ 241 (-51.41%)
Mutual labels:  laravel, sorting
Mailgun
Mailgun package for Laravel
Stars: ✭ 297 (-40.12%)
Mutual labels:  laravel, laravel-5-package
Auth Tests
Always-current tests for Laravel's authentication system. Curated by the community.
Stars: ✭ 230 (-53.63%)
Mutual labels:  laravel, laravel-5-package
Laravel Database Encryption
A package for automatically encrypting and decrypting Eloquent attributes in Laravel 5.5+, based on configuration settings.
Stars: ✭ 238 (-52.02%)
Mutual labels:  laravel, laravel-5-package
Generator
Laravel 5.3+ Scaffold Generator, Support both bootstrap and Semantic UI
Stars: ✭ 327 (-34.07%)
Mutual labels:  laravel, laravel-5-package
Telegram
✈️ Telegram Notifications Channel for Laravel
Stars: ✭ 450 (-9.27%)
Mutual labels:  laravel, laravel-5-package

Column sorting for Laravel 5.5-8

Latest Version Software License Total Downloads run-tests

Package for handling column sorting in Laravel 5.[5-8]. For earlier versions of Laravel checkout branch L5.1-3

Setup

Composer

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

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

Laravel's >=5.5 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)

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

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 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'])

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.

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 should be crystal clear and I advise you to skim it.

Font Awesome (default font classes)

Install Font-Awesome for visual Joy. Search "sort" in cheatsheet and see used icons (12) yourself.

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.

Full Example

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

Routes

Route::get('users', ['as' => 'users.index', 'uses' => '[email protected]']);

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->appends(\Request::except('page'))->render() !!}

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

HasOne / BelongsTo Relation sorting

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

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.

/**
 * 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 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

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)

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

...
$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 is useful when you want to sort results with withCount(), 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 $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.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].