Skip to content

Commit cffd2ef

Browse files
committed
Sorting Callbacks
- Add callback to sortable() - Add has/getSortCallback - Utilize callback when sorting - Add getColumn method
1 parent 3016ed0 commit cffd2ef

File tree

3 files changed

+50
-7
lines changed

3 files changed

+50
-7
lines changed

src/DataTableComponent.php

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,11 @@
1616
*/
1717
abstract class DataTableComponent extends Component
1818
{
19-
use WithBulkActions;
20-
use WithCustomPagination;
21-
use WithFilters;
22-
use WithPerPagePagination;
23-
use WithSorting;
19+
use WithBulkActions,
20+
WithCustomPagination,
21+
WithFilters,
22+
WithPerPagePagination,
23+
WithSorting;
2424

2525
/**
2626
* The default pagination theme.
@@ -190,4 +190,18 @@ public function render()
190190
'rows' => $this->rows,
191191
]);
192192
}
193+
194+
/**
195+
* Get a column object by its field
196+
*
197+
* @param $column
198+
*
199+
* @return mixed
200+
*/
201+
protected function getColumn($column)
202+
{
203+
return collect($this->columns())
204+
->where('column', $column)
205+
->first();
206+
}
193207
}

src/Traits/WithSorting.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,11 @@ public function sortBy(string $field): ?string
3030
public function applySorting(Builder $query): Builder
3131
{
3232
foreach ($this->sorts as $field => $direction) {
33-
$query->orderBy($field, $direction);
33+
if (optional($this->getColumn($field))->hasSortCallback()) {
34+
$query = app()->call($this->getColumn($field)->getSortCallback(), ['builder' => $query, 'direction' => $direction]);
35+
} else {
36+
$query->orderBy($field, $direction);
37+
}
3438
}
3539

3640
return $query;

src/Views/Column.php

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,11 @@ class Column
2424
*/
2525
public bool $sortable = false;
2626

27+
/**
28+
* @var null
29+
*/
30+
public $sortCallback;
31+
2732
/**
2833
* @var string|null
2934
*/
@@ -103,10 +108,14 @@ public function isBlank(): bool
103108
/**
104109
* @return $this
105110
*/
106-
public function sortable(): self
111+
public function sortable(callable $callback = null): self
107112
{
108113
$this->sortable = true;
109114

115+
if ($callback) {
116+
$this->sortCallback = $callback;
117+
}
118+
110119
return $this;
111120
}
112121

@@ -192,4 +201,20 @@ public function formatted($row, $column = null)
192201

193202
return $value;
194203
}
204+
205+
/**
206+
* @return bool
207+
*/
208+
public function hasSortCallback(): bool
209+
{
210+
return $this->sortCallback !== null;
211+
}
212+
213+
/**
214+
* @return callable|null
215+
*/
216+
public function getSortCallback(): ?callable
217+
{
218+
return $this->sortCallback;
219+
}
195220
}

0 commit comments

Comments
 (0)