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.
composer require mavinoo/laravel-batch
config/app.php:
'providers' => [
// ...
Mavinoo\Batch\BatchServiceProvider::class,
],
'aliases' => [
// ...
'Batch' => Mavinoo\Batch\BatchFacade::class,
],
id):
use App\Models\User;
$users = [
['id' => 1, 'status' => 'active'],
['id' => 2, 'status' => 'deactive'],
];
Batch::update(new User, $users, 'id');
Batch::update() or batch()->update() for simple bulk updates.HasBatch trait to models for direct method calls (e.g., User::batchUpdate()).update, updateMultipleCondition, and insert methods.updateMultipleCondition.id).$data = [
['id' => 1, 'status' => 'active', 'nickname' => 'Alice'],
['id' => 2, 'status' => 'deactive'],
];
Batch::update(User::class, $data, 'id');
$activeUsers = User::where('status', 'active')->get()->keyBy('id');
Batch::update($activeUsers, $data, 'id');
WHERE id=1 AND status='active').$conditions = [
['conditions' => ['id' => 1, 'status' => 'active'], 'columns' => ['nickname' => 'Admin']],
['conditions' => ['id' => 2], 'columns' => ['status' => 'pending']],
];
Batch::updateMultipleCondition(new User, $conditions, 'id');
conditions (WHERE clauses) and columns (SET values).last_login > 30 days").balance, quantity).$operations = [
['id' => 1, 'balance' => ['+', 100]], // Add 100
['id' => 2, 'quantity' => ['-', 5]], // Subtract 5
];
Batch::update(new User, $operations, 'id');
DB::transaction(function () {
Batch::update(new User, $operations, 'id');
// Log the transaction in an audit table
});
$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
batchSize (default: 500, min: 100) to avoid memory issues.email):
$existingEmails = User::pluck('email')->toArray();
$values = array_filter($values, fn($row) => !in_array($row[1], $existingEmails));
event(new UsersBulkInserted($result['totalRows']));
// In User.php
use Mavinoo\Batch\Traits\HasBatch;
class User extends Model {
use HasBatch;
}
// Usage:
User::batchUpdate($data, 'id');
User::batchInsert($columns, $values, 200);
$partialUpdates = [
['id' => 1, 'status' => 'active'], // Only updates status
['id' => 2, 'nickname' => 'Bob'], // Only updates nickname
];
Batch::update(new User, $partialUpdates, 'id');
ON CONFLICT clauses.// 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);
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
}
$result['totalRows']) for auditing.Database Driver Quirks:
Batch::disableBacktick(true); // Call before batch operations
id columns are unsigned integers to avoid overflow errors in batch inserts.Conditional Updates:
updateMultipleCondition: Fixed in v2.4.1. Ensure you’re using the latest version.OR clauses) may not leverage batch optimization. Simplify where possible.Arithmetic Operations:
['+', 100] (not strings like "+100").Batch Inserts:
INSERT IGNORE in MySQL or ON CONFLICT DO NOTHING in PostgreSQL).Model Integration:
HasBatch doesn’t conflict with other traits (e.g., SoftDeletes). Test with:
class User extends Model {
use HasBatch, SoftDeletes;
}
Transactions:
DB::transaction for atomicity:
DB::transaction(function () {
Batch::update(new User
How can I help you explore Laravel packages today?