Laravelですでに投稿してある記事をID順や日付順で並べ替えたいとき
composerでKyslik/column-sortableをインストール
% composer require kyslik/column-sortable
configに必要事項を追記
config\app.php
'providers' => [
.
.
.
/*
* 追加
*/
Kyslik\ColumnSortable\ColumnSortableServiceProvider::class,
]
投稿記事に関係するモデルに追記
app\Models\Record.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Kyslik\ColumnSortable\Sortable; //追記
class Record extends Model
{
use HasFactory;
use Sortable; // 追記
// テーブル名を明示
protected $table = 'records';
//可変項目
protected $fillable =
[
'date',
'subject',
'sum',
'user_id'
];
public $sortable =
[
'id',
'date',
'subject',
'sum',
'user_id'
];//追記(ソートに使うカラムを指定
関連するコントローラーを変更
Http\Controllers\RecordController.php
class RecordController extends Controller
{
/**
* ブログ一覧を表示する
*
* @return view
*/
public function index(){
$records = Record::sortable()->get(); //sortableメソッドを使用
return view('record.list',['records' => $records]);
}
自分自身はRecord::sortable()->get();
とするべきところをRecord::all()
としたままだったせいで先に進めず苦労した。
ビューを変更
resources\views\record\list.blade.php
<tr class='text-xl bg-gray-100 container mx-auto leading-10'>
<th class="px-8 mx-10">@sortablelink('id', 'ID')</th>
<th class="px-8 mx-10">@sortablelink('date', 'DATE')</th>
<th class="px-8 mx-10">@sortablelink('subject', 'SUBJECT')</th>
<th class="px-8 mx-10">@sortablelink('sum', 'SUM')</th>
<th class="px-8 mx-10">@sortablelink('user_id', 'USER')</th>
<th class="px-8 mx-10">@sortablelink('updated_at', 'UPDATED')</th>
<th></th>
<th></th>
</tr>
テーブル内の並べ替えたい項目の見出しを@sortablelink()
で作成する。
第1引数はカラム名、第2引数は表示される見出しの名前になる。
ひとまずこれで見出しをクリックしたら並べ替えられるところまではできた。
設定ファイルを変更して日本語対応にする
このままだと@sortablelink('name', '名前')
の'名前'
が半角英数字しか対応していない(全角にすると表示されない)ので、設定を変更する。
vendor/kyslik/column-sortable/src/ColumnSortable/SortableLink.php
$formatting_function = config('columnsortable.formatting_function', null);
if ( ! is_null($formatting_function) && function_exists($formatting_function)) {
if(!preg_match("/^[ぁ-んァ-ヶー一-龠]+$/u",$title)) //追記
$title = call_user_func($formatting_function, $title);
これで見出しを日本語にしても表示されるようになる。
resources\views\record\list.blade.php
<tr class='text-xl bg-gray-100 container mx-auto leading-10'>
<th class="text-blue-500 px-8 mx-10">@sortablelink('id', '番号')</th>
<th class="text-blue-500 px-8 mx-10">@sortablelink('date', '日付')</th>
<th class="text-blue-500 px-8 mx-10">@sortablelink('subject', '科目')</th>
<th class="text-blue-500 px-8 mx-10">@sortablelink('sum', '時間')</th>
<th class="text-blue-500 px-8 mx-10">@sortablelink('user_id', 'ユーザー')</th>
<th class="text-blue-500 px-8 mx-10">@sortablelink('updated_at', '更新日')</th>
<th></th>
<th></th>
</tr>