From a75c9ddb9981d680b010e53848a9f95b97c6296e Mon Sep 17 00:00:00 2001 From: Henrik Hautakoski Date: Sun, 2 Jan 2022 21:12:55 +0100 Subject: [PATCH] Adding app/Http/Livewire/Traits/WithSort.php --- app/Http/Livewire/Traits/WithSort.php | 51 +++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 app/Http/Livewire/Traits/WithSort.php diff --git a/app/Http/Livewire/Traits/WithSort.php b/app/Http/Livewire/Traits/WithSort.php new file mode 100644 index 0000000..704b66b --- /dev/null +++ b/app/Http/Livewire/Traits/WithSort.php @@ -0,0 +1,51 @@ +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); + } + } +}