kyslik/column-sortable
column-sortableパッケージをコンポーザーからインストール
php composer require kyslik/column-sortable
いろいろ設定
config.app.phpにサービスプロバイダ、エイリアスを追加
config/app.php
'providers' => [
....
Kyslik\ColumnSortable\ColumnSortableServiceProvider::class,
]
コンフィグファイル追加
php artisan vendor:publish --provider="Kyslik\ColumnSortable\ColumnSortableServiceProvider" --tag="config"
css 以下のアイコンを使っているみたい。
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css">
実装
ソートをしたいDBモデルに追加
<?php
namespace App;
use Kyslik\ColumnSortable\Sortable;//追記
class Modelname extends Model
{
use Sortable;//追記
protected $fillable = [ 'companyname_kana','email','status' ];
public $sortable = ['id','companyname_kana','email','status'];//(ソートに使うカラムを追記
//姓(セイ)・名(メイ)で分かれているカラムをつなげてマルチソートに
public function unionNameSortable($query, $direction){
return $query->orderBy('lastname_kana', $direction)->orderBy('firstname_kana', $direction);
bladeにリンクを設置
<th>@sortablelink('pref', '都道府県')</th>
//姓(セイ)・名(メイ)で分かれているカラムをつなげてマルチソートに
<th>@sortablelink('unionName', '氏名')</th>
ページャーを設置している場合は、ページャーにも並び替えクエリを追加しておきます
{{ $list->appends(request()->query())->links() }}
columnSortable.php
//olumnSortable.phpの上記部分を以下に変更
‘asc_suffix’ => ‘-up’,
‘desc_suffix’ => ‘-down’,
利用するclassはカラムごとに指定
columnSortable.phpの一番最初にあるcolumnsに、利用するclassが指定
alphaはa-z、amountは量、numericは数値のアイコン
'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',
],
],
参考サイトは以下。
https://qiita.com/anomeme/items/5475c5e8ba9136e73b4e
以下の方法【eloquent-sortable】でのソートもあるようですがよくわからなかった。
eloquent-sortable