导出操作
简介
Filament 包含一个可以将行数据导出到 CSV 或者 XLSX 文件的 Action。点击触发按钮后,会打开一个模态框询问用户要导出那些列,以及这些类要使用什么标签。该特性使用了队列批量操作及数据库通知,因此你需要发布这些迁移到 Laravel 中。同时,也需要发布 Filament 用于存储导出数据的迁移表:
# Laravel 11 and higher
php artisan make:queue-batches-table
php artisan make:notifications-table
# Laravel 10
php artisan queue:batches-table
php artisan notifications:table
# All apps
php artisan vendor:publish --tag=filament-actions-migrations
php artisan migrate
NOTE
如果你使用的是 PostgreSQL,请确保通知迁移中的 data 字段使用 json(): $table->json('data')。
NOTE
如果 User 模型使用了 UUID,请确保通知迁移的 notifiable 字段使用 uuidMorphs(): $table->uuidMorphs('notifiable')
ExportAction 可以像这样使用:
use App\Filament\Exports\ProductExporter;
use Filament\Actions\ExportAction;
ExportAction::make()
->exporter(ProductExporter::class)
如果你想将该 Action 添加到表头,可以这样使用:
use App\Filament\Exports\ProductExporter;
use Filament\Actions\ExportAction;
use Filament\Tables\Table;
public function table(Table $table): Table
{
return $table
->headerActions([
ExportAction::make()
->exporter(ProductExporter::class),
]);
}
Or if you want to add it as a table bulk action, so that the user can choose which rows to export, they can use Filament\Actions\ExportBulkAction:
use App\Filament\Exports\ProductExporter;
use Filament\Actions\ExportBulkAction;
use Filament\Tables\Table;
public function table(Table $table): Table
{
return $table
->toolbarActions([
ExportBulkAction::make()
->exporter(ProductExporter::class),
]);
}
需要创建 "exporter" 类,以告知 Filament 如何导处每一行。
创建导出器
要为模型创建 exporter 类,可以使用 make:filament-exporter 命令,并传入模型名称:
php artisan make:filament-exporter Product
该命令将在 app/Filament/Exports 目录下创建一个新类。你需要定义可被导处的列字段。
自动生成导出器列
如果你想节省时间,Filament 可以使用 --generate,基于模型的数据库字段,为你自动生成列字段:
php artisan make:filament-exporter Product --generate
定义导出器列
要定义可被导出的列,你需要在导出器类中重写 getColumns() 方法,并使其返回 ExportColumn 对象数组:
use Filament\Actions\Exports\ExportColumn;
public static function getColumns(): array
{
return [
ExportColumn::make('name'),
ExportColumn::make('sku')
->label('SKU'),
ExportColumn::make('price'),
];
}
自定义导出列标签
每个列的标签将由该列名称自动生成,不过你也可以调用 label() 方法对其进行重写:
use Filament\Actions\Exports\ExportColumn;
ExportColumn::make('sku')
->label('SKU')