Add UserExporter and UserImporter classes with export/import functionality
This commit is contained in:
85
app/Filament/Imports/UserImporter.php
Normal file
85
app/Filament/Imports/UserImporter.php
Normal file
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Imports;
|
||||
|
||||
use App\Models\User;
|
||||
use Filament\Actions\Imports\Exceptions\RowImportFailedException;
|
||||
use Filament\Actions\Imports\ImportColumn;
|
||||
use Filament\Actions\Imports\Importer;
|
||||
use Filament\Actions\Imports\Models\Import;
|
||||
use Str;
|
||||
|
||||
class UserImporter extends Importer
|
||||
{
|
||||
protected static ?string $model = User::class;
|
||||
|
||||
public static function getColumns(): array
|
||||
{
|
||||
return [
|
||||
ImportColumn::make('name')
|
||||
->requiredMapping()
|
||||
->exampleHeader('Name')
|
||||
->example('Admin')
|
||||
->label('Name')
|
||||
->rules(['required']),//, 'max:255'
|
||||
ImportColumn::make('email')
|
||||
->requiredMapping()
|
||||
->exampleHeader('Email')
|
||||
->example('admin@cripumps.com')
|
||||
->label('Email')
|
||||
->rules(['required', 'email']),//, 'max:255'
|
||||
ImportColumn::make('password')
|
||||
->requiredMapping()
|
||||
->exampleHeader('Password')
|
||||
->example('admin@pass')
|
||||
->label('Password')
|
||||
->rules(['required']),//, 'max:255'
|
||||
];
|
||||
}
|
||||
|
||||
public function resolveRecord(): ?User
|
||||
{
|
||||
$warnMsg = [];
|
||||
if (Str::length($this->data['name']) < 0) {
|
||||
$warnMsg[] = "User name not found";
|
||||
}
|
||||
// || !is_numeric($this->data['code']) || !preg_match('/^[1-9]\d{3,}$/', $this->data['code'])
|
||||
if (Str::length($this->data['email']) < 5) {
|
||||
$warnMsg[] = "Invalid email found";
|
||||
}
|
||||
if (Str::length($this->data['password']) < 3) {
|
||||
$warnMsg[] = "Invalid password found";
|
||||
}
|
||||
|
||||
if (!empty($warnMsg)) {
|
||||
throw new RowImportFailedException(implode(', ', $warnMsg));
|
||||
}
|
||||
|
||||
User::updateOrCreate([
|
||||
'email' => $this->data['email'],
|
||||
],
|
||||
[
|
||||
'name' => $this->data['name'],
|
||||
'password' => $this->data['password'],
|
||||
]);
|
||||
|
||||
return null;
|
||||
// return User::firstOrNew([
|
||||
// // Update existing records, matching them by `$this->data['column_name']`
|
||||
// 'email' => $this->data['email'],
|
||||
// ]);
|
||||
|
||||
//return new User();
|
||||
}
|
||||
|
||||
public static function getCompletedNotificationBody(Import $import): string
|
||||
{
|
||||
$body = 'Your user import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.';
|
||||
|
||||
if ($failedRowsCount = $import->getFailedRowsCount()) {
|
||||
$body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.';
|
||||
}
|
||||
|
||||
return $body;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user