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

Interact Laravel Package

milestone/interact

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install Dependencies

    composer require milestone/appframe
    composer require milestone/interact
    

    (Note: appframe is a prerequisite; ensure it’s properly configured.)

  2. Configure the Package Add the namespace of your table classes in config/interact.php:

    'table_namespace' => 'App\\Interact\\Tables',
    
  3. Create a Table Class Define a class matching your database table name (e.g., UserTable) in the configured namespace, implementing _Milestone\Interact\Table:

    namespace App\Interact\Tables;
    
    use Milestone\Interact\Table as _Table;
    
    class UserTable implements _Table {
        public $table = 'users';
        public $mode = 'insert'; // or 'update', 'delete'
        public $primary_key = 'id';
        public $data = []; // Optional: Default data for all records
    }
    
  4. First Use Case: Import Data Use the Interact facade to import data from a CSV/array:

    use Milestone\Interact\Facades\Interact;
    
    $result = Interact::import('UserTable', $dataArrayOrFilePath);
    

Implementation Patterns

1. Data Import Workflows

Basic Import

// Import from an array
$records = [['name' => 'John', 'email' => 'john@example.com']];
Interact::import('UserTable', $records);

// Import from a CSV file
Interact::import('UserTable', 'path/to/file.csv');

Bulk Operations

  • Batch Processing: For large datasets, chunk the data and process in loops:
    $chunkSize = 100;
    foreach (array_chunk($records, $chunkSize) as $chunk) {
        Interact::import('UserTable', $chunk);
    }
    

Dynamic Table Handling

  • Runtime Table Switching: Pass the table class dynamically:
    $tableClass = 'App\\Interact\\Tables\\ProductTable';
    Interact::import($tableClass, $data);
    

2. Validation & Hooks

Record-Level Validation

Override isValidImportRecord() to validate each record:

public function isValidImportRecord($record) {
    if (empty($record['email'])) {
        return 'Email is required';
    }
    return true; // or false
}

Pre/Post-Import Hooks

  • Modify Data Before Import:
    public function preImport($content) {
        // Transform data (e.g., normalize arrays)
        return array_map('strtolower', $content);
    }
    
  • Post-Import Actions:
    public function postImport($content, $result) {
        // Log results or trigger events
        return $result; // or modified result
    }
    

Record-Specific Callbacks

  • Post-Insert Actions:
    public function recordImported($record, $executionId) {
        // Send email, update related models, etc.
    }
    

3. Integration with Laravel Ecosystem

Queue Jobs for Large Imports

Wrap imports in a job to avoid timeouts:

use Milestone\Interact\Facades\Interact;
use Illuminate\Bus\Queueable;

class ImportUsersJob implements ShouldQueue {
    use Queueable;

    public function handle() {
        Interact::import('UserTable', $this->data);
    }
}

Laravel Events

Trigger events after import:

// In UserTable.php
public function postImport($content, $result) {
    event(new UsersImported($result));
}

Service Provider Binding

Extend the package via service providers:

public function register() {
    $this->app->bind('interact.table.user', function () {
        return new \App\Interact\Tables\UserTable();
    });
}

Gotchas and Tips

Pitfalls

  1. Namespace Mismatch

    • Ensure the table_namespace in config/interact.php matches your table classes’ namespace.
    • Fix: Double-check the config and autoloading.
  2. Primary Key Conflicts

    • If primary_key is misconfigured, updates/inserts may fail silently.
    • Tip: Use DB::table()->where(...)->update() for manual fallbacks.
  3. CSV Parsing Issues

    • The package assumes CSV files are properly formatted. Use League\Csv for complex parsing:
      use League\Csv\Reader;
      $csv = Reader::createFromPath('file.csv', 'r');
      $records = $csv->getRecords();
      
  4. Memory Limits

    • Large imports may hit PHP’s memory limit. Use chunking or queues.
  5. Case Sensitivity

    • Table names in $table must match the database exactly (including case).

Debugging Tips

  1. Enable Logging Add to config/interact.php:

    'debug' => env('INTERACT_DEBUG', false),
    

    Logs will appear in storage/logs/interact.log.

  2. Validate SQL Queries Use Laravel’s query logging:

    DB::enableQueryLog();
    Interact::import('UserTable', $data);
    dd(DB::getQueryLog());
    
  3. Test with Small Datasets Start with 1–2 records to verify hooks/validation before scaling.


Extension Points

  1. Custom Storage Adapters Override Milestone\Interact\Storage\FileStorage to support S3, databases, etc.

  2. Add New Modes Extend the mode property to support upsert, truncate, etc.:

    public $mode = 'upsert'; // Custom logic in the package
    
  3. Custom Result Objects Replace the default Result class by binding your own:

    $this->app->bind(
        Milestone\Interact\Result::class,
        App\Interact\CustomResult::class
    );
    
  4. Add Field Mappings Map CSV headers to database columns dynamically:

    public function preImport($content) {
        return array_map(function ($record) {
            return [
                'name' => $record['user_name'], // Map CSV 'user_name' to DB 'name'
                'email' => $record['email_address'],
            ];
        }, $content);
    }
    

Performance Optimizations

  • Disable Indexes Temporarily:
    DB::statement('ALTER TABLE users DISABLE KEYS');
    Interact::import('UserTable', $data);
    DB::statement('ALTER TABLE users ENABLE KEYS');
    
  • Batch Inserts: Use Laravel’s insert with chunking for raw performance:
    DB::table('users')->insert($chunk);
    
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.
craftcms/url-validator
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony