Archived
1
0
Fork 0

Adding app/Http/Livewire/Traits/WithSort.php

This commit is contained in:
Henrik Hautakoski 2022-01-02 21:12:55 +01:00
parent 18adbb4273
commit a75c9ddb99

View 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);
}
}
}