cms-laravel/app/Livewire/CustomTable.php

104 lines
2.9 KiB
PHP

<?php
namespace App\Livewire;
use Livewire\Component;
use Illuminate\Support\Facades\Http;
class CustomTable extends Component
{
public $data = [];
public $loading = false;
public $currentPage = 1;
public $pageSize = 10;
public $totalData = 0;
public $searchValue = '';
public $sortedInfo = null;
public $filteredInfo = [];
public $columns = [];
public $actions = [];
public $url;
public $keyValue = 'id';
// Initialize the component with URL, columns, actions, and key
public function mount($url, $columns, $actions = [], $keyValue = 'id')
{
$this->url = $url;
$this->columns = $columns;
$this->actions = $actions;
$this->keyValue = $keyValue;
$this->fetchData();
}
// Update data when search value changes (debounced in Blade)
public function updatedSearchValue()
{
$this->currentPage = 1; // Reset to first page on search
$this->fetchData();
}
// Toggle sorting for a column
public function sort($field)
{
if ($this->sortedInfo && $this->sortedInfo['field'] === $field) {
$this->sortedInfo['order'] = $this->sortedInfo['order'] === 'asc' ? 'desc' : 'asc';
} else {
$this->sortedInfo = ['field' => $field, 'order' => 'asc'];
}
$this->fetchData();
}
// Fetch data from the API
public function fetchData()
{
$this->loading = true;
$params = [
'_page' => $this->currentPage,
'_limit' => $this->pageSize,
'q' => $this->searchValue,
'_sort' => $this->sortedInfo ? $this->sortedInfo['field'] : null,
'_order' => $this->sortedInfo ? $this->sortedInfo['order'] : null,
];
try {
$response = Http::get($this->url, $params);
$this->data = $response->json('data') ?? []; // Adjust based on API response structure
$this->totalData = $response->json('total') ?? count($this->data);
} catch (\Exception $e) {
session()->flash('error', 'Failed to load data: ' . $e->getMessage());
} finally {
$this->loading = false;
}
}
// Handle pagination
public function handlePagination($page)
{
$this->currentPage = $page;
$this->fetchData();
}
// Handle page size change (optional extension)
public function handleSizeChange($size)
{
$this->pageSize = $size;
$this->currentPage = 1; // Reset to first page
$this->fetchData();
}
// Clear all filters, sorting, and search
public function handleClearAll()
{
$this->searchValue = '';
$this->sortedInfo = null;
$this->filteredInfo = [];
$this->currentPage = 1;
$this->fetchData();
}
// Render the Blade view
public function render()
{
return view('livewire.custom-table');
}
}