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

Laravel Batch Laravel Package

mavinoo/laravel-batch

Batch insert/bulk update helper for Laravel Eloquent. Update many rows in one query using an index key, or update per-row with multiple conditions. Includes Facade and helper access (Batch:: or batch()) for fast mass data changes.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require mavinoo/laravel-batch
    
  2. Register the service provider and facade in config/app.php:
    'providers' => [
        // ...
        Mavinoo\Batch\BatchServiceProvider::class,
    ],
    'aliases' => [
        // ...
        'Batch' => Mavinoo\Batch\BatchFacade::class,
    ],
    
  3. First use case: Batch update records by a shared index (e.g., id):
    use App\Models\User;
    
    $users = [
        ['id' => 1, 'status' => 'active'],
        ['id' => 2, 'status' => 'deactive'],
    ];
    Batch::update(new User, $users, 'id');
    

Where to Look First

  • Facade/Helper: Use Batch::update() or batch()->update() for simple bulk updates.
  • Model Integration: Add the HasBatch trait to models for direct method calls (e.g., User::batchUpdate()).
  • Documentation: Focus on the README examples for update, updateMultipleCondition, and insert methods.
  • Release Notes: Check v2.4.1 for fixes to updateMultipleCondition.

Implementation Patterns

Core Workflows

1. Bulk Updates by Index

  • Use Case: Update multiple records sharing a common column (e.g., id).
  • Pattern:
    $data = [
        ['id' => 1, 'status' => 'active', 'nickname' => 'Alice'],
        ['id' => 2, 'status' => 'deactive'],
    ];
    Batch::update(User::class, $data, 'id');
    
  • Integration Tip: Pair with Eloquent scopes to filter records before batching:
    $activeUsers = User::where('status', 'active')->get()->keyBy('id');
    Batch::update($activeUsers, $data, 'id');
    

2. Conditional Batch Updates

  • Use Case: Update records matching specific conditions per row (e.g., WHERE id=1 AND status='active').
  • Pattern:
    $conditions = [
        ['conditions' => ['id' => 1, 'status' => 'active'], 'columns' => ['nickname' => 'Admin']],
        ['conditions' => ['id' => 2], 'columns' => ['status' => 'pending']],
    ];
    Batch::updateMultipleCondition(new User, $conditions, 'id');
    
  • Workflow:
    1. Define an array of conditions (WHERE clauses) and columns (SET values).
    2. Use the model instance to dynamically build queries.
    3. Leverage for role-based updates or state transitions (e.g., "update all active users with last_login > 30 days").

3. Arithmetic Operations

  • Use Case: Batch increment/decrement/modify numeric fields (e.g., balance, quantity).
  • Pattern:
    $operations = [
        ['id' => 1, 'balance' => ['+', 100]], // Add 100
        ['id' => 2, 'quantity' => ['-', 5]],  // Subtract 5
    ];
    Batch::update(new User, $operations, 'id');
    
  • Integration Tip: Combine with transactions for financial systems:
    DB::transaction(function () {
        Batch::update(new User, $operations, 'id');
        // Log the transaction in an audit table
    });
    

4. Batch Inserts

  • Use Case: Insert large datasets efficiently (e.g., CSV imports, API bulk creates).
  • Pattern:
    $columns = ['name', 'email', 'status'];
    $values = [
        ['John', 'john@example.com', 'active'],
        ['Jane', 'jane@example.com', 'pending'],
    ];
    $result = Batch::insert(new User, $columns, $values, 200); // Batch size 200
    
  • Best Practices:
    • Chunking: Use batchSize (default: 500, min: 100) to avoid memory issues.
    • Validation: Validate data before insertion (e.g., unique email):
      $existingEmails = User::pluck('email')->toArray();
      $values = array_filter($values, fn($row) => !in_array($row[1], $existingEmails));
      
    • Post-Insert Actions: Trigger events or queue jobs after insertion:
      event(new UsersBulkInserted($result['totalRows']));
      

5. Model-Level Integration

  • Use Case: Encapsulate batch logic within models for reusability.
  • Pattern:
    // In User.php
    use Mavinoo\Batch\Traits\HasBatch;
    
    class User extends Model {
        use HasBatch;
    }
    // Usage:
    User::batchUpdate($data, 'id');
    User::batchInsert($columns, $values, 200);
    
  • Benefit: Keeps batch operations model-specific and self-documenting.

Advanced Patterns

Dynamic Column Handling

  • Use Case: Update only the columns provided in the batch (avoids overwriting unrelated fields).
  • Pattern:
    $partialUpdates = [
        ['id' => 1, 'status' => 'active'],       // Only updates status
        ['id' => 2, 'nickname' => 'Bob'],       // Only updates nickname
    ];
    Batch::update(new User, $partialUpdates, 'id');
    
  • Tip: Useful for partial API updates or gradual schema migrations.

PostgreSQL-Specific Optimizations

  • Use Case: Leverage PostgreSQL features like JSON fields or ON CONFLICT clauses.
  • Pattern:
    // Disable backticks for PostgreSQL (if needed)
    Batch::disableBacktick(true);
    // Insert with JSON data
    $values = [[1, '{"tags": ["admin", "premium"]}']];
    Batch::insert(new User, ['id', 'metadata'], $values);
    

Error Handling

  • Use Case: Gracefully handle failures in batch operations.
  • Pattern:
    try {
        $result = Batch::update(new User, $data, 'id');
        if (!$result) {
            throw new \RuntimeException("Batch update failed");
        }
    } catch (\Exception $e) {
        Log::error("Batch operation failed: " . $e->getMessage());
        // Retry or notify admins
    }
    
  • Tip: Log results (e.g., $result['totalRows']) for auditing.

Gotchas and Tips

Pitfalls

  1. Database Driver Quirks:

    • PostgreSQL/SQL Server: Disable backticks for certain operations:
      Batch::disableBacktick(true); // Call before batch operations
      
    • MySQL: Ensure id columns are unsigned integers to avoid overflow errors in batch inserts.
  2. Conditional Updates:

    • Bug in updateMultipleCondition: Fixed in v2.4.1. Ensure you’re using the latest version.
    • Performance: Complex conditions (e.g., OR clauses) may not leverage batch optimization. Simplify where possible.
  3. Arithmetic Operations:

    • Syntax: Use arrays for operations: ['+', 100] (not strings like "+100").
    • Overflow: Large increments/decrements may cause integer overflow. Validate data first.
  4. Batch Inserts:

    • Batch Size: Default is 500, but adjust based on your server’s memory (e.g., 100 for low-memory environments).
    • Unique Constraints: Inserts ignore duplicates by default (use INSERT IGNORE in MySQL or ON CONFLICT DO NOTHING in PostgreSQL).
  5. Model Integration:

    • Trait Conflicts: Ensure HasBatch doesn’t conflict with other traits (e.g., SoftDeletes). Test with:
      class User extends Model {
          use HasBatch, SoftDeletes;
      }
      
  6. Transactions:

    • No Built-in Support: Batch operations do not wrap in transactions by default. Use Laravel’s DB::transaction for atomicity:
      DB::transaction(function () {
          Batch::update(new User
      
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