think.studio / nova-resource-dynamic-export
动态导出资源的功能。
1.0.0
2023-09-06 05:20 UTC
Requires
- php: ^8.1
- laravel/nova: ^4.0
- maatwebsite/laravel-nova-excel: ^1.3
- think.studio/laravel-json-field-cast: ^2.1
- think.studio/nova-html-field: ^2.3
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.21
- orchestra/testbench: ^8.5
- phpunit/phpunit: ^10.2
- psalm/plugin-laravel: ^2.8
- vimeo/psalm: ^5.13
README
动态导出资源的功能。
安装
您可以通过composer安装此包
composer require think.studio/nova-resource-dynamic-export # optional publish configs php artisan vendor:publish --provider="NovaResourceDynamicExport\ServiceProvider" --tag="config"
如果您将使用默认的存储磁盘,请更新文件系统配置。
// config/filesystems.php 'exports' => [ 'driver' => 'local', 'root' => storage_path('app/exports'), ],
并将资源添加到您的管理后台
// Providers/NovaServiceProvider.php protected function resources(): void { parent::resources(); Nova::resources([ \NovaResourceDynamicExport\Nova\Resources\ExportStoredFile::class, ]); }
请记住为\NovaResourceDynamicExport\Models\ExportStoredFile模型或您的自定义模型添加策略
使用方法
通用资源导出操作
public function actions(NovaRequest $request): array { return [ \NovaResourceDynamicExport\Nova\Actions\ExportResourceAction::make() ->askForFilename() ->askForWriterType() ->askForColumns([ 'id', 'title' => 'Fund title', 'publication_status', 'description', 'color_code', 'selected_report', ]) ->setPostReplaceFieldValuesWhenOnResource(function ($array, \App\Models\Fund $model, $only) { if (in_array('selected_report', $only)) { $array['selected_report'] = $model->selectedReport->report_date?->format('Y-m-d'); } return $array; }), ]; }
自定义指定导出
首先创建自定义导出类
// Exports/PostsWithTagBreaking.php use Illuminate\Database\Eloquent\Builder; use Maatwebsite\Excel\Concerns\Exportable; use Maatwebsite\Excel\Concerns\FromQuery; use Maatwebsite\Excel\Concerns\WithHeadings; use Maatwebsite\Excel\Concerns\WithMapping; use NovaResourceDynamicExport\Export\CustomExport; use NovaResourceDynamicExport\Tests\Fixtures\Models\Post; class PostsWithTagBreaking extends CustomExport implements FromQuery, WithHeadings, WithMapping { use Exportable; public function query() { return Post::query() ->whereHas('tags', fn (Builder $q) => $q->where('name', 'Breaking')); } public function headings(): array { return [ 'Title', 'content', ]; } /** * @param Post $row */ public function map($row): array { return [ 'title' => $row->title, 'content' => $row->content, ]; } }
然后使用任何服务提供者添加此类
// Providers/NovaServiceProvider.php public function boot(): void { parent::boot(); CustomResourcesExport::use(PostsWithTagBreaking::class); }
这就是全部,在ExportStoredFile资源索引中您将看到新的执行自定义导出的操作