Livewire Datatable: adding delete/restore functionality as livewire actions instead of regular controller actions.
This commit is contained in:
parent
7c49bb8cf7
commit
170a53e473
2 changed files with 58 additions and 22 deletions
|
|
@ -10,7 +10,7 @@ use Illuminate\Support\Str;
|
|||
|
||||
class Datatable extends Component
|
||||
{
|
||||
use WithPagination, Traits\WithSort;
|
||||
use WithPagination, Traits\WithSort, Traits\Alert;
|
||||
|
||||
/**
|
||||
* Query string settings.
|
||||
|
|
@ -55,14 +55,14 @@ class Datatable extends Component
|
|||
public $route_edit;
|
||||
|
||||
/**
|
||||
* Route for deleting a record (if null, link is omitted)
|
||||
* True if delete functionality is enabled.
|
||||
*/
|
||||
public $route_delete;
|
||||
public $delete_enabled;
|
||||
|
||||
/**
|
||||
* Route for restoring a record (if null, link is omitted)
|
||||
* True if restore functionality is enabled.
|
||||
*/
|
||||
public $route_restore;
|
||||
public $restore_enabled;
|
||||
|
||||
/**
|
||||
* How many records should be displayed on one page.
|
||||
|
|
@ -71,7 +71,7 @@ class Datatable extends Component
|
|||
|
||||
public function mount(string $model, array $columns,
|
||||
array $sort_columns = [], $default_sort = '',
|
||||
$route_create = null, $route_edit = null, $route_delete = null, $route_restore = null)
|
||||
$route_create = null, $route_edit = null, $delete_enabled = false, $restore_enabled = false)
|
||||
{
|
||||
$this->model = app()->make($model);
|
||||
$this->default_sort = $default_sort;
|
||||
|
|
@ -79,12 +79,54 @@ class Datatable extends Component
|
|||
$this->sort_columns = $sort_columns;
|
||||
$this->route_create = $route_create;
|
||||
$this->route_edit = $route_edit;
|
||||
$this->route_delete = $route_delete;
|
||||
$this->route_restore = $route_restore;
|
||||
$this->delete_enabled = (bool) $delete_enabled;
|
||||
$this->restore_enabled = (bool) $restore_enabled;
|
||||
|
||||
$this->setTrashedColumns();
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete an record
|
||||
*/
|
||||
public function delete($id)
|
||||
{
|
||||
if (!$this->delete_enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
$record = $this->model->find($id);
|
||||
|
||||
if (!$record) {
|
||||
$this->danger('Record not found');
|
||||
return;
|
||||
}
|
||||
|
||||
$record->delete();
|
||||
|
||||
$this->info(__("Record #:id was deleted.", [ 'id' => $record->id ]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore a delted record
|
||||
*/
|
||||
public function restore($id)
|
||||
{
|
||||
if (!$this->restore_enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
$record = $this->model->withTrashed()->find($id);
|
||||
|
||||
if (!$record) {
|
||||
$this->danger('Record not found');
|
||||
return;
|
||||
}
|
||||
|
||||
$record->restore();
|
||||
|
||||
$this->info(__("Record #:id was restored.", [ 'id' => $record->id ]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the datatable
|
||||
*/
|
||||
|
|
|
|||
Reference in a new issue