2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Laravel10で sort機能を実装 矢印クリックで昇順・降順を選べるようにする

Last updated at Posted at 2023-02-22

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

image.png

参考サイトは以下。
https://qiita.com/anomeme/items/5475c5e8ba9136e73b4e

以下の方法【eloquent-sortable】でのソートもあるようですがよくわからなかった。

eloquent-sortable

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?