Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Ti Ext Importexport Laravel Package

igniterlabs/ti-ext-importexport

ImportExport extension for TastyIgniter: export menu items, customers, reservations and orders to CSV, edit offline, then import updates back into your site. Simple CSV-based data migration and bulk updates for TastyIgniter records.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require igniterlabs/ti-ext-importexport -W
   php artisan igniter:up
  1. Access Admin Panel: Navigate to Tools > Import/Export in the TastyIgniter admin dashboard.

    • Use the built-in Menu Items, Orders, or Customers export/import options immediately.
  2. First Use Case:

    • Export: Select "Menu Items" → Click "Export" → Download CSV → Edit in Excel → Re-import.
    • Import: Upload a CSV (e.g., from a supplier) → Map columns → Process.

Implementation Patterns

Core Workflows

  1. Admin Panel Integration:

    • Leverage the pre-built UI under Tools > Import/Export for quick operations.
    • Use the registerImportExport() method in your extension’s Extension class to add custom types:
      public function registerImportExport(): array {
          return [
              'import' => [
                  'my_custom_import' => [
                      'label' => 'Custom Data Import',
                      'model' => \App\Models\CustomImport::class,
                      'configFile' => 'extension::models/custom_import',
                      'permissions' => 'Extension.ManageImports',
                  ],
              ],
              'export' => [
                  'my_custom_export' => [
                      'label' => 'Custom Data Export',
                      'model' => \App\Models\CustomExport::class,
                      'configFile' => 'extension::models/custom_export',
                      'permissions' => 'Extension.ManageExports',
                  ],
              ],
          ];
      }
      
  2. Custom Model Patterns:

    • Imports: Extend IgniterLabs\ImportExport\Models\ImportModel and implement importData():

      public function importData(array $data): void {
          foreach ($data as $record) {
              $validated = Validator::validate($record, [
                  'field1' => 'required|string',
                  'field2' => 'nullable|integer',
              ]);
              // Save logic...
          }
      }
      
      • Use logCreated(), logUpdated(), and logError() for tracking.
    • Exports: Extend IgniterLabs\ImportExport\Models\ExportModel and implement exportData():

      public function exportData(array $columns, array $options = []): array {
          return $this->newQuery()
              ->where('active', 1)
              ->get($columns)
              ->toArray();
      }
      
  3. Configuration Files: Define column mappings and UI options in resources/models/{type}.php:

    return [
        'columns' => [
            'id' => 'ID',
            'name' => 'Name',
            'price' => 'Price (USD)',
        ],
        'fields' => [
            'update_existing' => [
                'label' => 'Update Existing Records',
                'type' => 'switch',
                'default' => true,
            ],
        ],
    ];
    
  4. File Handling:

    • Imports: Files are auto-uploaded to storage/app/imports/. Use storage_path('app/imports') to access.
    • Exports: Files are streamed directly to the browser with headers like:
      return response()->streamDownload(function () {
          $this->generateCsv($data);
      }, 'export_' . now() . '.csv');
      
  5. Validation & Error Handling:

    • Validate data in importData() using Laravel’s Validator.
    • Log errors with logError($rowNumber, $message) for admin review.

Gotchas and Tips

Pitfalls

  1. Column Mismatches:

    • Ensure CSV columns match the columns array in your config file. Use snake_case for DB fields.
    • Fix: Add a pre-import validation step:
      if (!array_key_exists('expected_column', $data[0])) {
          $this->logError(1, "Missing required column: 'expected_column'");
          return;
      }
      
  2. Large File Timeouts:

    • Imports/exports with >10,000 rows may hit PHP’s max_execution_time.
    • Fix: Use chunking in exportData():
      return $this->newQuery()->chunk(500, function ($records) {
          // Process chunks...
      })->toArray();
      
  3. Permission Issues:

    • Custom types require explicit permissions (e.g., 'Extension.ManageImports').
    • Fix: Register permissions in your extension’s registerPermissions() method.
  4. Excel vs. CSV:

    • The package primarily supports CSV. For Excel (.xlsx), use a library like PhpOffice/PhpSpreadsheet and pre-process files:
      $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file);
      $data = $spreadsheet->getActiveSheet()->toArray();
      
  5. Database Locking:

    • Concurrent imports/exports may cause deadlocks on large tables.
    • Fix: Add transactions or use DB::connection()->disableSharedLocks().

Debugging Tips

  1. Log Inspection:

    • Check import/export logs in the admin panel under Tools > Import/Export > History.
    • For custom types, log to Laravel’s log channel:
      \Log::debug('Import data', ['data' => $data]);
      
  2. CSV Parsing Errors:

    • Use League\Csv\Reader directly to debug:
      $csv = Reader::createFromPath($filePath, 'r');
      $csv->setHeaderOffset(0);
      foreach ($csv as $record) {
          // Inspect $record
      }
      
  3. Configuration Overrides:

    • Override default settings (e.g., delimiter) via service provider:
      $this->app->singleton('importExport.config', function () {
          return [
              'csv_delimiter' => ';', // Default is ','
          ];
      });
      

Extension Points

  1. Custom Field Types: Extend the UI with custom field types (e.g., dropdowns) by publishing assets:

    public function boot() {
        $this->loadViewsFrom(__DIR__.'/views', 'import_export');
        $this->publishes([
            __DIR__.'/views' => resource_path('views/vendor/import_export'),
        ]);
    }
    
  2. Pre/Post Hooks: Add logic before/after imports/exports via events:

    // In EventServiceProvider
    protected $listen = [
        'igniter.import.before' => [
            \App\Listeners\PreImportLogic::class,
        ],
        'igniter.export.after' => [
            \App\Listeners\PostExportLogic::class,
        ],
    ];
    
  3. API Integration: Expose imports/exports via API by creating a controller:

    public function export(Request $request) {
        $export = new \App\Models\CustomExport();
        return $export->download($request->columns);
    }
    
  4. Bulk Operations: Optimize for bulk updates by using upsert:

    DB::table('table')->upsert($data, ['id'], ['name', 'price']);
    
  5. Localization: Translate column labels and messages:

    'columns' => [
        'name' => trans('import_export.columns.name'),
    ],
    

    Add translations to resources/lang/{locale}/import_export.php.


---
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor