Laravel Bulk Insert PostgreSQL COPY for Lightning Speed
You're pulling data from an external feed and need to dump five‑million rows into a PostgreSQL table. Using Eloquent's insert() in a loop will choke the app and blow the request timeout. The trick for a laravel bulk insert postgresql copy is to let the database do the heavy lifting.
TL;DR / Quick Summary
Docker with Laravel 11, PHP 8.3, PostgreSQL 15.
Create a CSV stream in
app/Services/PostgresCopyImporter.php.Call
COPYviaDB::connection('pgsql')->raw($sql)inside a transaction.Fallback to chunked
insert()when the driver is MySQL.Verify rows with
SELECT COUNT(*).
Prerequisites
Docker Compose file exposing
pgsqlandlaravel.testservices.pgsqlconnection configured inconfig/database.php.Large dataset ready as an array of associative rows.
# docker-compose.yml (excerpt)
services:
laravel.test:
image: laravelphp/php-fpm:8.3
volumes:
- ./:/var/www/html
depends_on:
- pgsql
pgsql:
image: postgres:15-alpine
environment:
POSTGRES_DB: app
POSTGRES_USER: app
POSTGRES_PASSWORD: secret
ports:
- "5432:5432"Generate a CSV Stream
Create a service that turns an array into a pipe‑delimited CSV string without touching the filesystem.
// app/Services/PostgresCopyImporter.php
<?php
namespace App\Services;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class PostgresCopyImporter
{
/**
* @param string $table Target table name
* @param array $columns Ordered column list
* @param iterable $rows Generator yielding associative rows
*/
public function import(string $table, array $columns, iterable $rows): void
{
$csv = $this->streamCsv($columns, $rows);
$sql = "COPY {$table} (" . implode(', ', $columns) . ") FROM STDIN WITH (FORMAT csv, DELIMITER '|', NULL '\\N')";
DB::connection('pgsql')->transaction(function () use ($sql, $csv) {
$pdo = DB::connection('pgsql')->getPdo();
$stmt = $pdo->prepare($sql);
$stmt->execute();
$pdo->pgsqlCopyFromStdIn($stmt, $csv);
});
}
private function streamCsv(array $columns, iterable $rows): string
{
$handle = fopen('php://temp', 'r+');
foreach ($rows as $row) {
$line = [];
foreach ($columns as $col) {
$value = $row[$col] ?? null;
$line[] = $value === null ? '\\N' : Str::replace('|', '\\|', (string) $value);
}
fputcsv($handle, $line, '|', '\\');
}
rewind($handle);
$csv = stream_get_contents($handle);
fclose($handle);
return $csv;
}
}Note:
pgsqlCopyFromStdInis a thin wrapper around PDO'spgsqlCopyFromthat you can add to a helper trait. The implementation is omitted for brevity.
Run the COPY Command
Wire the service into a controller or a queued job.
// app/Http/Controllers/ImportController.php
<?php
namespace App\Http\Controllers;
use App\Services\PostgresCopyImporter;
use Illuminate\Http\Request;
class ImportController extends Controller
{
public function store(Request $request, PostgresCopyImporter $importer)
{
$data = $this->fetchLargePayload(); // returns iterable of rows
$columns = ['id', 'name', 'email', 'created_at'];
$importer->import('users', $columns, $data);
return response()->json(['status' => 'ok']);
}
}The request finishes in seconds even with a million rows because the database streams the CSV directly.
Transaction Safety
If the COPY fails, the surrounding transaction rolls back automatically. For extra safety, catch \PDOException and log the offending line.
DB::connection('pgsql')->transaction(function () use ($sql, $csv) {
try {
$pdo = DB::connection('pgsql')->getPdo();
$stmt = $pdo->prepare($sql);
$stmt->execute();
$pdo->pgsqlCopyFromStdIn($stmt, $csv);
} catch (\PDOException $e) {
// Log $e->getMessage() and the first 5 lines of $csv for debugging
throw $e; // triggers rollback
}
});Fallback for MySQL Environments
Not every deployment runs PostgreSQL. Detect the driver at runtime and switch to chunked Eloquent inserts.
if (DB::getDriverName() === 'pgsql') {
$importer->import('users', $columns, $data);
} else {
// MySQL fallback – 1,000 rows per chunk
collect($data)->chunk(1000)->each(function ($chunk) use ($columns) {
\DB::table('users')->insert($chunk->toArray());
});
}Verification
After the job runs, confirm the row count.
php artisan tinker --execute "echo DB::table('users')->count();"You should see the exact number of rows you fed into the importer.
Comparison Table
Approach | Rows per second | Memory impact | Code complexity |
|---|---|---|---|
Eloquent | ~500 | High (holds all models) | Low |
Chunked | ~5,000 | Medium (chunks) | Medium |
PostgreSQL | >100,000 | Low (stream only) | High |
Common Pitfalls & Troubleshooting
"invalid input syntax for type" – CSV delimiter mismatch. Ensure the same delimiter (
|) is declared in bothfputcsvand theCOPYstatement.Permission denied on STDIN – Docker's
postgresuser must haveCOPYrights. Grant withGRANT INSERT ON TABLE users TO app;.Large CSV string OOM – If the dataset exceeds available RAM, switch
streamCsvto write directly to a temporary file (php://temp) and pass the file path toCOPY FROM PROGRAM.Transaction deadlock – Do not mix
COPYwith other writes on the same table inside the same transaction.
FAQ
How does COPY compare to
insert()in Laravel? COPY streams raw CSV to the server, bypassing PHP's per‑row overhead, so it can ingest millions of rows in seconds.Can I use COPY with a remote PostgreSQL instance? Yes, as long as the connection user has
SUPERUSERorCOPYprivileges and the server allows STDIN.What if my CSV contains line breaks? Set
FORMAT csvand letfputcsvhandle quoting; the pipe delimiter prevents accidental splits.Is the approach safe for production traffic? Absolutely – the operation runs inside a transaction, rolls back on error, and does not lock the whole table for reads.
If you run into timeout issues while the COPY runs, check out our guide on Fix Laravel PostgreSQL Timeouts with PgBouncer Pooling for connection‑pool tweaks.
Connect with KoderSolution 🚀
Master modern software engineering, scalable architectures, and advanced backend systems with KoderSolution:
🌐 Official Website: Read more architectural deep-dives and tutorials on kodersolution.com
📺 YouTube Channel: Subscribe to @kodersolution on YouTube for concise, animated system design breakdowns and shorts.
📱 Facebook Page: Follow our official Facebook Page for daily development tips, architecture discussions, and community updates.
💬 What's your setup? Have you tried streaming massive CSV payloads into PostgreSQL from Laravel before? Share any quirks you hit when scaling the COPY approach in a high‑traffic production app. Share your thoughts and join the discussion below!