eightynine/filament-excel-import

使用 Laravel Filament 导入 Excel 文件。

3.1.3 2024-08-29 05:26 UTC

This package is auto-updated.

Last update: 2024-08-29 05:30:03 UTC


README

Latest Version on Packagist Total Downloads

此包为您的 filament 资源添加了新功能,允许您轻松将数据导入到您的模型中

此包将 maatwebsite/laravel-excel 的功能引入到 filament 中。您可以在您的 laravel 项目中使用所有 maatwebsite/laravel-excel 功能

🛠️ 加入我们的旅程

嗨,我是 Eighty Nine。我创建了 excel 导入插件来解决我作为开发者遇到的实际问题。您的赞助将使我能够投入更多时间来改进这些工具并帮助更多人。 成为赞助者 并加入我,为开发者社区做出积极贡献。

安装

您可以通过 composer 安装此包

composer require eightynine/filament-excel-import

用法

在使用此动作之前,请确保为您的模型允许 批量赋值。如果您正在执行自定义导入,则此步骤不是必需的。

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Client extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'phone', 'email'];
}

例如,如果您在项目中有一个 'ClientResource',可以将此动作集成到以下示例中的 ListClients 类中

namespace App\Filament\Resources\ClientResource\Pages;

use App\Filament\Resources\ClientResource;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;

class ListClients extends ListRecords
{
    protected static string $resource = ClientResource::class;

    protected function getHeaderActions(): array
    {
        return [
            \EightyNine\ExcelImport\ExcelImportAction::make()
                ->color("primary"),
            Actions\CreateAction::make(),
        ];
    }
}

自定义导入流程

使用闭包

您可以使用闭包来处理导入后的集合。

    protected function getHeaderActions(): array
    {
        return [
            \EightyNine\ExcelImport\ExcelImportAction::make()
                ->processCollectionUsing(function (string $modelClass, Collection $collection) {
                    // Do some stuff with the collection
                    return $collection;
                }),
            Actions\CreateAction::make(),
        ];
    }

使用您自己的导入类

如果您希望使用自己的导入类来更改导入流程,您可以创建自己的导入类。

php artisan make:import MyClientImport

然后在您的动作中使用您的客户端导入类

    protected function getHeaderActions(): array
    {
        return [
            \EightyNine\ExcelImport\ExcelImportAction::make()
                ->slideOver()
                ->color("primary")
                ->use(App\Imports\MyClientImport::class),
            Actions\CreateAction::make(),
        ];
    }

表单定制

您可以通过使用 beforeUploadFieldafterUploadField 方法来定制表单。这些方法接受一个数组,该数组将添加到上传字段之前和之后。您还可以使用 uploadField 方法来定制上传字段。

    protected function getHeaderActions(): array
    {
        return [
            \EightyNine\ExcelImport\ExcelImportAction::make()
                ->slideOver()
                ->color("primary")
                ->use(App\Imports\MyClientImport::class)
                // Add fields before the upload field
                ->beforeUploadField([
                    TextInput::make('default_password'),
                    TextInput::make('default_status'),
                ])
                // Or add fields after the upload field
                ->afterUploadField([
                    TextInput::make('default_password'),
                    TextInput::make('default_status'),
                ])
                // Or customise the upload field
                ->uploadField(
                    fn ($upload) => $upload
                    ->label("Some other label")
                )
                // Use the additional form fields data
                ->beforeImport(function (array $data, $livewire, $excelImportAction) {
                    $defaultStatus = $data['default_status'];
                    $defaultPassword = $data['default_password'];

                    // When adding the additional data, the data will be merged with 
                    // the row data when inserting into the database
                    $excelImportAction->additionalData([
                        'password' => $defaultPassword,
                        'status' => $defaultStatus
                    ]);

                    // Do some other stuff with the data before importing
                })
                ,
            Actions\CreateAction::make(),
        ];
    }

自定义上传磁盘

要使用自定义上传磁盘,您可以发布配置文件并自定义上传_disk 配置。

php artisan vendor:publish --tag=excel-import-config

然后在您的配置文件中,您可以自定义上传_disk 配置。

return [
    /**
     * File upload path
     * 
     * Customise the path where the file will be uploaded to, 
     * if left empty, config('filesystems.default') will be used
     */
    'upload_disk' => 's3',
];

在导入前后执行操作

您可以使用 beforeImport 和 afterImport 闭包在导入前后执行操作。

$data 是通过表单提交的数据,这意味着文件上传也存在于 $data['upload'] 中,而 $livewire 是正在执行操作的 Livewire 实例(在这种情况下,是 ListClients 类)。

    protected function getHeaderActions(): array
    {
        return [
            \EightyNine\ExcelImport\ExcelImportAction::make()
                ->slideOver()
                ->color("primary")
                ->use(App\Imports\MyClientImport::class)
                ->beforeImport(function ($data, $livewire, $excelImportAction) {
                    // Perform actions before import
                })
                ->afterImport(function ($data, $livewire, $excelImportAction) {
                    // Perform actions after import
                }),
            Actions\CreateAction::make(),
        ];
    }

数据验证

您可以使用 validateUsing 方法在导入之前验证数据。此方法接受一个规则数组,该数组用于验证数据。您可以使用 Laravel 验证系统中的所有规则。

    protected function getHeaderActions(): array
    {
        return [
            \EightyNine\ExcelImport\ExcelImportAction::make()
                ->validateUsing([
                    'name' => 'required',
                    'email' => 'required|email',
                    'phone' => ['required','numeric'],
                ]),
            Actions\CreateAction::make(),
        ];
    }

验证前后修改数据

在某些情况下,您可能需要在验证前后修改数据,以便实现此目的,您可以使用 mutateBeforeValidationUsingmutateAfterValidationUsing 函数方法。

    \EightyNine\ExcelImport\ExcelImportAction::make()
        ->mutateBeforeValidationUsing(function(array $data): array{
            $data['date'] = Carbon::make((string) str($value)->replace('.', '-'));
            return $data;
        })
        ->validateUsing([
            'name' => 'required',
            'email' => 'required|email',
            'phone' => ['required','numeric'],
        ])
        ->mutateAfterValidationUsing(function(array $data): array{
            $data['date'] = $data['date']->format('Y-m-d');
            return $data;
        }),

测试

composer test

更新日志

有关最近更改的更多信息,请参阅 更新日志

贡献

有关详细信息,请参阅 贡献指南

安全漏洞

有关报告安全漏洞的详细信息,请参阅 我们的安全策略

致谢

许可证

MIT许可证(MIT)。请参阅许可证文件获取更多信息。