To consume an external API and display the data using pagination in Filament without saving the customers to the database, you can create a custom paginator and a resource page in Filament that will handle the API requests and display the data.
Here's a step-by-step solution:
- Create a Custom Paginator: You'll need to create a custom paginator that can handle the API response and provide pagination functionality.
use Illuminate\Pagination\LengthAwarePaginator;
class ApiPaginator extends LengthAwarePaginator
{
public static function fromApiResponse($response, $perPage, $currentPage)
{
$total = $response['total'] ?? 0;
$items = collect($response['data'] ?? []);
return new static($items, $total, $perPage, $currentPage, [
'path' => request()->url(),
'query' => request()->query(),
]);
}
}
-
Create a Filament Resource: Generate a Filament resource for the customers. You can use the
php artisan make:filament-resource Customercommand to create a basic resource. -
Customize the Resource List Page: In the resource's
Pages/ListCustomers.phpfile, override thegetQuerymethod to fetch data from the external API and use the custom paginator.
use Filament\Resources\Pages\ListRecords;
use Illuminate\Support\Facades\Http;
class ListCustomers extends ListRecords
{
protected function getQuery()
{
$perPage = 10; // Define how many items you want per page
$currentPage = request()->input('page', 1);
// Replace with the actual API endpoint
$response = Http::get('https://api.external-service.com/customers', [
'page' => $currentPage,
'perPage' => $perPage,
])->json();
// Use the custom paginator to create a LengthAwarePaginator
$paginator = ApiPaginator::fromApiResponse($response, $perPage, $currentPage);
return $paginator;
}
}
-
Customize the Resource Table:
In the resource's
Pages/ListCustomers.phpfile, you can define the columns that you want to display in the table.
protected function getTableColumns(): array
{
return [
// Define your columns here, for example:
TextColumn::make('name'),
TextColumn::make('email'),
// Add more columns as needed
];
}
- Handle API Authentication (if needed): If the API requires authentication, make sure to include the necessary headers or parameters when making the request.
$response = Http::withHeaders([
'Authorization' => 'Bearer ' . $yourApiToken,
])->get('https://api.external-service.com/customers', [
'page' => $currentPage,
'perPage' => $perPage,
]);
- Display the Resource in Filament: Finally, you can navigate to the Filament admin panel, and you should see the customers listed with pagination.
Remember to replace placeholders like https://api.external-service.com/customers and $yourApiToken with the actual values for your API. Also, adjust the perPage variable and the columns to match your API's pagination and data structure.