diff --git a/app/Http/Livewire/Datatable.php b/app/Http/Livewire/Datatable.php new file mode 100644 index 0000000..2d2df3c --- /dev/null +++ b/app/Http/Livewire/Datatable.php @@ -0,0 +1,93 @@ + ['except' => 'id'], + 'dir' => ['except' => 'asc'], + 'page' => ['except' => 1] + ]; + + /** + * Model to get data from. + */ + public $model; + + /** + * Array of columns to show + */ + public array $columns; + + /** + * What colums are sortable + */ + public array $sort_columns; + + /** + * Route for editing a record (if null, link is omitted) + */ + public $route_edit; + + /** + * Route for deleting a record (if null, link is omitted) + */ + public $route_delete; + + /** + * How many records should be displayed on one page. + */ + public int $itemsPerPage = 30; + + public function mount(string $model, array $columns, array $sort_columns = [], + $default_sort = '', $route_delete = null, $route_edit = null) + { + $this->model = app()->make($model); + $this->sort = $default_sort; + $this->sort_columns = $sort_columns; + $this->route_edit = $route_edit; + $this->route_delete = $route_delete; + } + + /** + * Render the datatable + */ + public function render() + { + $query = $this->model->query(); + + // Check colums for "dot-notated" strings. + // as we want to eager load those relationships + foreach ($this->columns as $col => $_) { + $p = strrpos($col, '.'); + if ($p !== false) { + $rel = substr($col, 0, $p); + $query->with($rel); + } + } + + // Apply sorting. + $this->sortApply($query); + + $items = $query->paginate($this->itemsPerPage); + + return view('livewire.datatable', ['items' => $items]); + } + + public function getRouteKeyProperty() + { + return Str::slug(get_class($this->model)); + } +} diff --git a/resources/views/livewire/datatable.blade.php b/resources/views/livewire/datatable.blade.php new file mode 100644 index 0000000..8321b61 --- /dev/null +++ b/resources/views/livewire/datatable.blade.php @@ -0,0 +1,57 @@ +
|
+ @if (isset($sort_columns[$key]))
+
+ {{ __($name) }}
+
+ @else
+ {{ $name }}
+ @endif
+ |
+ @endforeach
+
+ @if($route_delete || $route_edit)
+ {{ __('Actions') }} | + @endif +
|---|---|
| {{ Arr::get($item, $key) }} | + @endforeach + +
+ @if($route_edit)
+
+ |
+