fusic/laravel-sortable

2.0.0 2023-11-02 07:13 UTC

This package is auto-updated.

Last update: 2024-08-31 00:27:52 UTC


README

轻松生成用于切换排序状态的链接,例如 <table> 等。

安装

将此存储库添加到 composer.json,然后执行 $ composer install

"repositories": [
        {
            "type": "vcs",
            "url": "git@github.com:fusic/laravel-sortable.git"
        }
    ]

将服务提供者注册到 config/app.php

'providers' => [
    ...
    /*
    * Package Service Providers...
    */
    Sortable\Providers\SortableServiceProvider::class,
    ...
]

用法

创建 Sortable 类

执行 artisan make:sortable 命令。

$ php artisan make:sortable EmployeeSortable

设置

在创建的 Sortable 类中写入排序键。

<?php

namespace App\Sort;

use Sortable\Sortable;

class EmployeeSortable extends Sortable
{
    public function __construct()
    {
        $this->params = [  // write here!
            'employee_number',
            'name' => 'Employees.fullname',  // URL parameter => column name
            'birthday' => function ($builder, $query, $sortKey, $sortDirection) {
                // write custom 'order by' condition
                return $builder->orderBy('foo', 'desc');
            },
        ];
    }
}

将 Sortable 对象插入查询

$employees = Employees::query()
    ->where('foo', 'baz')
    /** what you want... **/
    ->sort(new EmployeeSortable())
    /** ... **/
    ;

这将向查询添加排序条件。 Sortable 可用于 Eloquent 和 Query Builder。

在 blade 中使用 @sort 指令

生成简单链接

@sort(['title' => 'Name', 'key' => 'name', 'url' => '#'])

@sort 指令将生成一个链接以切换排序状态,如下所示

<a href="https://www.example.com/index?sort=name&direction=asc" class="sort-key">Name</a>

状态按升序、降序和无排序的顺序切换,生成的链接也按此顺序。

用法示例

<table>
    <thead>
        <tr>
            <th>@sort(['title' => 'Number', 'key' => 'employee_number', 'url' => '#'])</th>
            <th>@sort(['title' => 'Name', 'key' => 'name', 'url' => '#'])</th>
            <th>@sort(['title' => 'Birthday', 'key' => 'birthday', 'url' => '#'])</th>
        </tr>
    </thead>
    <tbody>
        @foreach($employees as $employee)
        <tr>
            <td>{{ $employee->employee_number }}</td>
            <td>{{ $employee->fullname }}</td>
            <td>{{ $employee->birthday->format('Y/m/d') }}</td>
        </tr>
        @endforeach
    </tbody>
</table>

使用自定义 DOM 模板生成链接

将对应于每个排序状态的 DOM 模板传递给 @sort 指令,Sortable 将根据它生成链接。

@sort([
    'key' => 'name',
    'default' => '<span class="text-black">Name</span>',
    'asc' => '<span class="text-red asc">Name↑</span>',
    'desc' => '<span class="text-blue desc">Name↓</span>',
])

这将生成一个自定义链接

<a href="https://www.example.com/index?sort=name&direction=asc" class="sort-key"><span class="text-red asc">Name↑</span></a>