51 lines
779 B
PHP
51 lines
779 B
PHP
<?php
|
|
|
|
namespace App\Http\Livewire\Traits;
|
|
|
|
trait WithSort {
|
|
|
|
/**
|
|
* Sort column
|
|
*/
|
|
public string $sort = '';
|
|
|
|
/**
|
|
* Sort direction
|
|
*/
|
|
public string $dir = 'asc';
|
|
|
|
/**
|
|
* Sort by column.
|
|
*/
|
|
public function sort($column)
|
|
{
|
|
if (!array_key_exists($column, $this->sort_columns)) {
|
|
return;
|
|
}
|
|
|
|
if ($this->sort === $column) {
|
|
$this->dir = $this->dir === 'asc' ? 'desc' : 'asc';
|
|
} else {
|
|
$this->sort = $column;
|
|
$this->reset('dir');
|
|
}
|
|
}
|
|
|
|
protected function sortApply($query)
|
|
{
|
|
// No sorting. bail out.
|
|
if (!strlen($this->sort)) {
|
|
return;
|
|
}
|
|
|
|
$columns = $this->sort_columns[$this->sort];
|
|
|
|
if (!is_array($columns)) {
|
|
$columns = [ $columns ];
|
|
}
|
|
|
|
foreach($columns as $column) {
|
|
$query->orderBy($column, $this->dir);
|
|
}
|
|
}
|
|
}
|