Adding app/Http/Livewire/Traits/WithSort.php
This commit is contained in:
parent
18adbb4273
commit
a75c9ddb99
1 changed files with 51 additions and 0 deletions
51
app/Http/Livewire/Traits/WithSort.php
Normal file
51
app/Http/Livewire/Traits/WithSort.php
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
<?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_map)) {
|
||||
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_map[$this->sort];
|
||||
|
||||
if (!is_array($columns)) {
|
||||
$columns = [ $columns ];
|
||||
}
|
||||
|
||||
foreach($columns as $column) {
|
||||
$query->orderBy($column, $this->dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in a new issue