Installation
composer require contextualcode/content-import
Add the bundle to config/bundles.php (Symfony) or config/app.php (Laravel):
ContextualCode\ContentImportBundle\ContentImportBundle::class => ['all' => true],
Basic Configuration Publish the default config:
php artisan vendor:publish --tag=content-import-config
Key settings to review:
default_import_path (where to store import files)supported_formats (e.g., ['csv', 'json', 'xml'])mapping_strategies (how to map imported data to your models)First Use Case: CSV Import
Create a CSV file (users_import.csv) with headers matching your User model fields:
email,name,role
[email protected],John Doe,admin
Run the import command:
php artisan import:run --file=users_import.csv --model=App\Models\User
Pre-Import Validation
Extend ContentImportBundle\Validator\ImportValidator to add custom rules:
use ContentImportBundle\Validator\Constraints as ImportAssert;
/**
* @ImportAssert\FileExists(path="/path/to/import")
* @ImportAssert\ValidCSV(delimiter=",")
*/
public function validateImport()
{
// Custom logic
}
Mapping Strategies Define how imported data maps to your Eloquent models:
// config/packages/contextualcode_content_import.yaml
mapping_strategies:
App\Models\User:
- { source: 'email', target: 'email', type: 'string' }
- { source: 'role', target: 'role', type: 'enum', options: ['admin', 'user'] }
Chunked Processing For large datasets, use chunking in your service:
$importer = $this->container->get('content_import.importer');
$importer->import($filePath, User::class, [
'chunk_size' => 100,
'on_chunk' => function ($chunk) {
// Process chunk (e.g., log, validate)
}
]);
Post-Import Actions Hook into events to trigger actions after import:
// In a service provider
$this->app->booted(function () {
event(new ContentImportEvents\PostImport(User::class, $importedCount));
});
Laravel Scout Integration Reindex search after import:
$importer->import($filePath, Product::class)->then(function () {
Product::reindex();
});
Queue Large Imports Dispatch a job for background processing:
dispatch(new ImportContentJob($filePath, User::class));
Custom Format Support
Extend ContentImportBundle\Reader\FileReaderInterface for new formats (e.g., Excel):
class ExcelReader implements FileReaderInterface
{
public function read(string $filePath): array
{
return Excel::toArray(new UserImport, $filePath);
}
}
Field Mismatches
debug: true
Check logs for MappingError exceptions.Memory Limits
chunk_size in config or stream processing:
chunk_size: 50
stream: true
Transaction Rollbacks
DB::transaction(function () use ($importer) {
$importer->import($filePath, User::class);
});
Timezone Handling
timezone: 'UTC'
Dry Run Mode Test mappings without writing to DB:
php artisan import:run --dry-run --file=users.csv
Log Imports
Enable logging in config/packages/contextualcode_content_import.yaml:
logging:
enabled: true
channel: single
Custom Error Handling Override the default error handler:
$importer->setErrorHandler(function ($error) {
\Log::error("Import Error: {$error->getMessage()}");
// Custom logic (e.g., notify admin)
});
Custom Validators Create a validator for domain-specific rules:
class UniqueEmailValidator extends ImportValidator
{
public function validateEmail($email, $row)
{
return !User::where('email', $email)->exists();
}
}
Pre/Post-Import Hooks Use events to extend functionality:
// Listen for pre-import
ContentImportEvents::PRE_IMPORT->listen(function ($event) {
$event->setOption('validate_emails', true);
});
Dynamic Model Mapping Resolve models dynamically (e.g., from a config file):
$mapping = config("import.mappings.{$event->getModel()}");
How can I help you explore Laravel packages today?