Weave 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

Laravel Batch provides bulk insert and update helpers for Laravel models. Use Batch::update with a key column or updateMultipleCondition for per-row conditions, making large data changes faster and cleaner without repetitive queries. Includes a facade and batch() helper.

View on GitHub
Deep Wiki
Context7
v3.3.0

Counter and conditional upserts, rows back from upserts, a report of skipped duplicates, fast imports, row validation and exports. Everything is additive, so upgrading from 3.2 needs no code changes:

composer update mavinoo/laravel-batch

Added

Counter upserts

Batch::upsert(new Stock, $rows, ['sku'], ['qty' => ['+']]);   // qty = stored qty + new qty
  • ['-'], ['max'] and ['min'] work the same way, on every database.

Conditional upserts

Batch::upsert(new Product, $rows, ['sku'], null, ['onlyIf' => ['updated_at' => '>']]);
  • Updates an existing row only when the new value wins. New rows are always inserted.

Rows back, and the duplicates that were skipped

$users  = Batch::upsertReturning(new User, $rows, ['email'], ['name'], ['id', 'email']);
$result = Batch::insertOrIgnoreRows(new User, $rows, ['email']);
// ['inserted' => 98, 'skipped' => [['email' => '[email protected]', ...], ...]]
  • insertOrIgnoreRows() was checked with 8 concurrent writers inserting overlapping keys on MySQL 8.4, MariaDB and PostgreSQL. Every row was reported by the connection that inserted it.

Fast imports

Batch::import(new Order, storage_path('orders.csv'), ['fast' => true]);
  • Uses COPY on PostgreSQL and LOAD DATA LOCAL INFILE on MySQL and MariaDB.
  • Bad values that MySQL would silently store with a warning throw instead, and nothing is written.
1,000,000-row CSV import fast
PostgreSQL 18.7 s 6.6 s
MySQL 8.4 18.7 s 8.4 s
MariaDB 12.6 s 6.4 s

Row validation in imports

Batch::import(new User, 'users.csv', ['rules' => ['email' => 'required|email']]);
// ['totalRows' => 9988, 'skipped' => 12, 'errors' => [15 => ['email' => [...]]]]

Export

User::where('active', true)->exportTo(storage_path('users.csv'), ['maxRows' => 100000]);
  • Writes CSV, TSV or JSON Lines files (also gzipped), a chunk at a time with constant memory.
  • maxRows splits the output into numbered parts.

Turn timestamps off

User::withoutTimestamps(fn () => Batch::update(new User, $rows)) now has documentation and tests for every method (#97).

Changed

  • upsert() takes an optional fifth $options argument.
  • import() also returns an errors key.

Full changelog: https://github.com/mavinoo/laravelBatch/blob/master/CHANGELOG.md Pull request: https://github.com/mavinoo/laravelBatch/pull/128

v3.1.0

New ways to write batches, a preview mode, and much faster large updates. Everything is additive, so upgrading from 3.0 needs no code changes:

composer update mavinoo/laravel-batch

Added

  • updateByKeys(): update rows matched on any number of key columns.
  • insertRows(): insert rows given as column => value pairs.
  • upsert(): insert or update in one query, with timestamps (created_at only on new rows), enums, and large batches split automatically in one transaction.
  • deleteByKeys(): delete rows matched on one or more key columns. Models using SoftDeletes are soft deleted unless $force is true.
  • pretend(): see the SQL and bindings a call would run, without running it or connecting to the database.
  • Static HasBatch methods for every operation: batchUpdateMultipleCondition(), batchUpdateWithTwoIndex(), batchUpdateByKeys(), batchInsertRows(), batchUpsert(), batchDeleteByKeys().

Faster updates

Each UPDATE ... CASE statement now holds at most 100 rows. The database checks every row against the CASE branches one by one, so large statements slowed down quickly.

Updating 50,000 rows 3.0.0 3.1.0
MySQL 8.4 30.5 s 3.1 s
MariaDB 10.11 25.3 s 2.4 s
PostgreSQL 16 over 15 min 2.5 s
SQLite 3.45 3.7 s 3.4 s

Deprecated

  • The instance method (new Model)->updateMultipleCondition(); use the static Model::batchUpdateMultipleCondition(). It will be removed in 4.0.

Also

  • Clearer InvalidArgumentExceptions for rows that aren't arrays, non-string column names and invalid arithmetic operators.
  • PHPStan level 9 with Larastan now runs in CI.

Full changelog: https://github.com/mavinoo/laravelBatch/blob/v3.1.0/CHANGELOG.md Pull request: https://github.com/mavinoo/laravelBatch/pull/125

v3.0.0

A major release that rewrites how queries are built. Every 2.x user should upgrade: all 2.x versions build SQL by escaping values by hand, which allows SQL injection (always on PostgreSQL, and through index values and JSON keys on every database). 3.0 sends every value as a bound parameter and lets Laravel's grammar quote every column and table name.

composer require "mavinoo/laravel-batch:^3.0"

Requires PHP 8.1+ and Laravel 10 – 13. Upgrading from 2.x takes a few minutes for most projects: see the upgrade guide.

Breaking changes

  • The $raw argument is removed. Wrap only the values that are SQL in DB::raw(): ['id' => 1, 'score' => DB::raw('score * 2')]. Passing true for the old argument throws, so a missed call never stores SQL as text.
  • Update methods return int and insert() returns array. Empty input returns 0 / zero counts instead of false.
  • Invalid input throws InvalidArgumentException before anything is written.
  • BatchInterface and Batch declare return types.
  • Mavinoo\Batch\Common\Common and the global str() helper are removed.

Added

  • Laravel 13 support.
  • DB::raw() in values, index values and conditions.
  • Enum values in every method.
  • Batches over the database's bound parameter limit are split automatically and run in one transaction on the model's connection.
  • A test suite (composer test) and GitHub Actions on PHP 8.1 – 8.5, Laravel 10 – 13, MySQL, MariaDB, PostgreSQL and SQLite.

Fixed

  • Quotes, backslashes, JSON, leading zeros and booleans are stored exactly as given (#66, #68, #70, #73, #76, #96, #101).
  • Every method works on PostgreSQL and SQLite (#116).
  • updateMultipleCondition() with string keys, on PostgreSQL, with null conditions, and when a condition column is updated in the same call on MySQL.
  • updated_at only changes for rows that change, on every database (#120).
  • Models with CREATED_AT or UPDATED_AT set to null (#107).
  • insert() rolls back on the model's own connection, and $insertIgnore works on PostgreSQL and SQLite.

Full changelog: https://github.com/mavinoo/laravelBatch/blob/v3.0.0/CHANGELOG.md Pull request: https://github.com/mavinoo/laravelBatch/pull/124

v2.4.1

fixed bugs! in method update Multiple Condition 146182143.

v2.3.6

Determine database driver from model, not default config Changelog https://github.com/AdairHomes/laravelBatch/commit/8eeca0c169e72faab2c568f7cb9e2d93e05710a4

v2.3.3

Insert and update batch (bulk) in laravel

support to the case where there is no 0th array
As it stands now, this would be an error in this case.

bug fixed: commit

v2.3.2

Insert and update batch (bulk) in laravel

bug fixed.

v2.3.1

Insert and update batch (bulk) in laravel

more bugs fixed.

v2.3.0

Insert and update batch (bulk) in laravel

update method insert, disableBacktick for driver pgsql & sqlsrv

v2.2.9

Insert and update batch (bulk) in laravel

add method disableBacktick for driver pgsql & sqlsrv

v2.2.8

Insert and update batch (bulk) in laravel

postgreSQL: add, Check Json types postgreSQL: fixed json data single quotes

v2.2.7

Insert and update batch (bulk) in laravel

Use Carbon:now() instead of the now() helper

v2.2.6

Insert and update batch (bulk) in laravel

Add support pgsql for updateWithTwoIndex

v2.2.5

Insert and update batch (bulk) in laravel

Fixed increment/decrement functionality

v2.2.4

Insert and update batch (bulk) in laravel

Added increment/decrement functionality

v2.2.3

Insert and update batch (bulk) in laravel

Fixed Bug

v2.2.2

Insert and update batch (bulk) in laravel

Fixed Bug

v2.2.1

Insert and update batch (bulk) in laravel

add method updateWithTwoIndex

v2.2.0

Insert and update batch (bulk) in laravel

Added support for pgsql batch update maintain the created_at and updated_at columns automatically

v2.1.9
v2.1.8
v2.1.7

rename class && namespace LaravelBatch to Batch

v2.1.5

Insert and update batch (bulk) in laravel Rename Class Batch to LaravelBatch & all package.

v2.1.4

Insert and update batch (bulk) in laravel

add insert ignore
v2.1.3

Insert and update batch (bulk) in laravel

Checks database connection on insert method
v2.1.2

Insert and update batch (bulk) in laravel

add file interface
add file helpers
add function batch()
v2.0.1

Insert and update batch (bulk) in laravel

v2.0

Insert and update batch (bulk) in laravel

v1.0

Laravel Batch updateBatch

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.
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator
equipc/laravel-email-database-log
adedsec/nova-translated-labels
wazza/laravel-db-encryption
hokny/laravel-generator
vonsogt/backup
jengo/queues
jeremykenedy/laravel-observability
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums
rlacerda83/query-parser
socialdept/atp-orm
cboxdk/laravel-assistant-client
socialdept/atp-resolver
socialdept/tenant-domains
tautvydasr/blade-class-names