PHP code example of mavinoo / laravel-batch
1. Go to this page and download the library: Download mavinoo/laravel-batch library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
mavinoo / laravel-batch example snippets
use App\Models\User;
use Mavinoo\Batch\BatchFacade as Batch;
$affected = Batch::update(new User, [
['id' => 1, 'status' => 'active', 'nickname' => 'Mohammad'],
['id' => 5, 'status' => 'deactive'],
['id' => 10, 'date' => now()],
], 'id');
Batch::update(new User, [
['id' => 1, 'balance' => ['+', 500]], // add
['id' => 2, 'balance' => ['-', 200]], // subtract
['id' => 3, 'balance' => ['*', 5]], // multiply
['id' => 4, 'balance' => ['/', 2]], // divide
['id' => 5, 'balance' => ['%', 2]], // modulo
]);
use Illuminate\Support\Facades\DB;
Batch::update(new User, [
['id' => 1, 'last_seen_at' => DB::raw('NOW()')],
['id' => 2, 'score' => DB::raw('score * 2 + bonus')],
]);
Batch::update(new User, [
['id' => 1, 'settings->theme' => 'dark', 'settings->notify->email' => false],
['id' => 2, 'settings->theme' => 'light'],
]);
Batch::update(new User, [['id' => 1, 'settings' => ['theme' => 'dark']]]);
Batch::updateWithTwoIndex(new Membership, [
['user_id' => 1, 'team_id' => 3, 'role' => 'admin'],
['user_id' => 2, 'team_id' => 3, 'role' => 'member'],
], 'user_id', 'team_id');
Batch::updateByKeys(new Score, [
['org_id' => 1, 'year' => 2025, 'code' => 'A', 'points' => 10],
['org_id' => 1, 'year' => 2026, 'code' => 'B', 'points' => 20],
], ['org_id', 'year', 'code']);
Batch::updateMultipleCondition(new User, [
[
'conditions' => ['id' => 1, 'status' => 'active'],
'columns' => ['status' => 'invalid', 'nickname' => 'mohammad'],
],
[
'conditions' => ['id' => 2],
'columns' => ['nickname' => 'mavinoo', 'name' => 'mohammad'],
],
], 'id');
$result = Batch::insert(new User, ['name', 'email', 'is_active'], [
['Mohammad', '[email protected] ', true],
['Saeed', '[email protected] ', false],
['Avin', '[email protected] ', true],
], 500);
// ['totalRows' => 3, 'totalBatch' => 500, 'totalQuery' => 1]
Batch::insertRows(new User, [
['name' => 'Mohammad', 'email' => '[email protected] '],
['email' => '[email protected] ', 'name' => 'Saeed'],
], 500);
$ids = Batch::insertGetIds(new User, [
['name' => 'Ali', 'email' => '[email protected] '],
['name' => 'Sara', 'email' => '[email protected] '],
]);
// [101, 102]
$result = Batch::insertOrIgnoreRows(new User, $rows, ['email']);
// ['inserted' => 98, 'skipped' => [['email' => '[email protected] ', 'name' => 'Ali'], ...]]
Batch::upsert(new User, [
['email' => '[email protected] ', 'name' => 'Ali', 'score' => 90], // exists: name and score are updated
['email' => '[email protected] ', 'name' => 'Sara', 'score' => 75], // new: inserted
], ['email'], ['name', 'score']);
Batch::upsert(new Stock, [
['sku' => 'A1', 'qty' => 5], // exists: qty = qty + 5
['sku' => 'B2', 'qty' => 10], // new: inserted with qty 10
], ['sku'], ['qty' => ['+']]);
// Rows from an external API: keep whichever version was changed last.
Batch::upsert(new Product, $rows, ['sku'], null, ['onlyIf' => ['updated_at' => '>']]);
$users = Batch::upsertReturning(new User, $rows, ['email'], ['name'], ['id', 'email']);
// [['id' => 7, 'email' => '[email protected] '], ['id' => 102, 'email' => '[email protected] ']]
Batch::deleteByKeys(new Score, [
['org_id' => 1, 'year' => 2025],
['org_id' => 2, 'year' => 2026],
], ['org_id', 'year']);
$result = Batch::sync(Product::where('supplier_id', 5), $feedRows, ['sku']);
// ['inserted' => 120, 'updated' => 4800, 'deleted' => 35]
// The same, on the query:
Product::where('supplier_id', 5)->syncRows($feedRows, ['sku']);
$result = Batch::import(new User, storage_path('users.csv'), [
'mode' => 'upsert', // 'insert' (default), 'insertIgnore' or 'upsert'
'uniqueBy' => ['email'],
'update' => ['name'],
'map' => ['E-mail' => 'email', 'Full name' => 'name'], // only mapped columns are imported
'transform' => fn (array $row) => $row['email'] ? $row : null, // null skips the row
]);
// ['totalRows' => 25000, 'skipped' => 12]
$result = Batch::import(new User, 'users.csv', [
'rules' => ['email' => '> ['The email field must be a valid email address.']], ...]]
Batch::import(new Order, storage_path('orders.csv'), ['fast' => true]);
$parts = Batch::splitFile(storage_path('users.csv'), lines: 50000);
// ['.../users-001.csv', '.../users-002.csv', ...]
Batch::splitFile($path, bytes: 100 * 1024 * 1024); // at most 100 MB per part
Batch::splitFile($path, lines: 50000, bytes: 50_000_000); // whichever comes first
Batch::export(User::where('active', true), storage_path('users.csv'), [
'columns' => ['id', 'email', 'name'],
'maxRows' => 100000, // users-001.csv, users-002.csv, ...
]);
// ['totalRows' => 250000, 'files' => ['.../users-001.csv', '.../users-002.csv', '.../users-003.csv']]
User::where('active', true)->exportTo(storage_path('users.jsonl')); // on the query
// Delete
Batch::deleteInChunks(Log::where('created_at', '<', now()->subYear()), chunk: 10000, sleepMs: 100);
// Update every matching row with the same values
Batch::updateInChunks(User::where('active', false), ['status' => 'archived'], chunk: 5000);
// Move rows into another table
Batch::archive(Order::where('created_at', '<', '2020-01-01'), 'orders_archive', chunk: 5000);
Log::where('created_at', '<', now()->subYear())->deleteInChunks(10000);
User::where('active', false)->updateInChunks(['status' => 'archived']);
Order::where('created_at', '<', '2020-01-01')->archiveTo('orders_archive');
DB::table('logs')->where('level', 'debug')->deleteInChunks();
User::withoutTimestamps(fn () => Batch::update(new User, $rows)); // updated_at is left alone
$queries = Batch::pretend(function ($batch) {
$batch->update(new User, [['id' => 1, 'name' => 'Ali']]);
});
// [['sql' => 'UPDATE `users` SET ... WHERE `id` IN (?)', 'bindings' => [...], 'connection' => 'mysql']]
use Illuminate\Database\Eloquent\Model;
use Mavinoo\Batch\Traits\HasBatch;
class User extends Model
{
use HasBatch;
}
User::batchUpdate($values, 'id');
User::batchUpdateWithTwoIndex($values, 'user_id', 'team_id');
User::batchUpdateByKeys($values, ['org_id', 'year']);
User::batchUpdateMultipleCondition($items, 'id');
User::batchInsert($columns, $values, 500);
User::batchInsertRows($rows, 500);
User::batchInsertGetIds($rows, 500);
User::batchImport(storage_path('users.csv'), ['mode' => 'upsert', 'uniqueBy' => ['email']]);
User::batchUpsert($rows, ['email'], ['name']);
User::batchUpsertReturning($rows, ['email'], ['name'], ['id', 'email']);
User::batchInsertOrIgnoreRows($rows, ['email']);
User::batchDeleteByKeys($rows, ['org_id', 'year']);
User::where('active', false)->deleteInChunks(1000);
User::where('active', false)->updateInChunks(['status' => 'archived']);
User::where('created_at', '<', '2020-01-01')->archiveTo('users_archive');
User::where('org_id', 5)->syncRows($rows, ['email']);
User::where('active', true)->exportTo(storage_path('users.csv'));
batch()->update(new User, $values, 'id');
batch()->insert(new User, $columns, $values, 500);