|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Illegal\LaravelUtils\Contracts\Livewire; |
| 4 | + |
| 5 | +/** |
| 6 | + * A sortable trait for livewire list components. |
| 7 | + * Import the trait in your livewire component than: |
| 8 | + * 1. Use the contructor to populate $this->sortDefaultField with the field that should be sorted by default. |
| 9 | + * 2. Use the contructor to populate $this->sortFields with the fields that can be sorted (key = query string field, value = table field). |
| 10 | + * |
| 11 | + * If you want to persist the sort field and direction in the url, use the following code in your livewire component: |
| 12 | + * 1. Declare a protected $queryString array. |
| 13 | + * 2. Use the contructor to populate the $queryString array with the sortField and sortDirection. |
| 14 | + * |
| 15 | + * For example: |
| 16 | + * ```php |
| 17 | + * $this->queryString = [ |
| 18 | + * 'sortField' => ['except' => $this->sortDefaultField], |
| 19 | + * 'sortDirection' => ['except' => $this->sortDirection] |
| 20 | + * ]; |
| 21 | + * ``` |
| 22 | + */ |
| 23 | +trait Sortable |
| 24 | +{ |
| 25 | + /** |
| 26 | + * @var string $sortDefaultField The default sort field. |
| 27 | + */ |
| 28 | + public string $sortDefaultField = ""; |
| 29 | + |
| 30 | + /** |
| 31 | + * @var string $sortField The current sort field. |
| 32 | + */ |
| 33 | + public string $sortField = ""; |
| 34 | + |
| 35 | + /** |
| 36 | + * @var string $sortDirection The current sort direction. |
| 37 | + */ |
| 38 | + public string $sortDirection = 'desc'; |
| 39 | + |
| 40 | + /** |
| 41 | + * @var array $sortFields The fields that can be sorted. |
| 42 | + */ |
| 43 | + public array $sortFields = []; |
| 44 | + |
| 45 | + /** |
| 46 | + * Sort the table by the given field. |
| 47 | + * |
| 48 | + * @param string $field The field to sort by. |
| 49 | + * @return void |
| 50 | + */ |
| 51 | + public function sortBy(string $field): void |
| 52 | + { |
| 53 | + if ($this->sortField === $field) { |
| 54 | + $this->sortDirection = $this->sortDirection == 'asc' ? 'desc' : 'asc'; |
| 55 | + } else { |
| 56 | + $this->sortField = $field; |
| 57 | + $this->sortDirection = 'asc'; |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + /** |
| 62 | + * Get the sort array. |
| 63 | + * |
| 64 | + * @return array The sort array, first value is the field and the second value is the direction. |
| 65 | + */ |
| 66 | + protected function getSort(): array |
| 67 | + { |
| 68 | + /** |
| 69 | + * Allow only fields that are in the $sortFields array and direction can only be asc or desc |
| 70 | + */ |
| 71 | + $this->sortField = in_array($this->sortField, $this->sortFields) ? $this->sortField : $this->sortDefaultField; |
| 72 | + $this->sortDirection = in_array($this->sortDirection, ['asc', 'desc']) ? $this->sortDirection : 'desc'; |
| 73 | + |
| 74 | + return [$this->sortField, $this->sortDirection]; |
| 75 | + } |
| 76 | +} |
0 commit comments