Sooner or later every system has to swallow somebody else's data: a supplier's price list, an export from the tool being replaced, a spreadsheet that has been the source of truth for five years. The first import script is usually written in an afternoon and works on the sample file. Then it meets the real file.
The real file has duplicate rows, identifiers that a spreadsheet has turned into scientific notation, dates in three formats and a column whose meaning changed halfway down. The import stops at row 8,412, and now there is a harder question than how to fix the parser: what state is the database in, and is it safe to run this again?
A reliable import is one where that question always has the same answer — yes. This is how to build one.
Make it idempotent
An import is idempotent when running it twice leaves the same result as running it once. That single property removes most of the fear: a crash, a timeout or a corrected source file all have the same remedy, which is to run it again.
It depends on every source record having a stable identity — something that does not change between runs and does not depend on the order of rows.
- Good: the source system's own ID, an ISBN or SKU, a natural key such as supplier code plus item code.
- Bad: the row number, an auto-increment on your side, the title.
Store that identity on the imported record, together with where it came from:
Schema::table('posts', function (Blueprint $table) {
$table->string('source_platform')->nullable();
$table->string('source_site')->nullable();
$table->string('source_id')->nullable();
$table->index(['source_platform', 'source_site', 'source_id']);
});
The site is part of the key for a reason. Record 42 from one system and record 42 from another are different things; an import that matches on the ID alone will eventually overwrite one with the other.
With the identity in place, the write becomes an upsert:
Post::updateOrCreate(
['source_platform' => 'wordpress', 'source_site' => $site, 'source_id' => $row['id']],
['title' => $row['title'], 'content' => $content, 'imported_at' => now()],
);
Read the file as a stream
Loading a whole file into memory works until the file is large — and export files are routinely hundreds of megabytes. Read one record at a time instead, so memory use stays flat whatever the size.
For CSV that is a generator:
function rows(string $path): Generator
{
$handle = fopen($path, 'rb');
$header = fgetcsv($handle);
while (($line = fgetcsv($handle)) !== false) {
yield array_combine($header, $line);
}
fclose($handle);
}
For XML, a pull parser does the same job. XMLReader moves through the document node by node, and only the element you are standing on is expanded:
$reader = new XMLReader();
$reader->open($path, 'UTF-8', LIBXML_NONET);
while ($reader->read()) {
if ($reader->nodeType === XMLReader::ELEMENT && $reader->name === 'item') {
$item = $reader->expand();
// ...handle one item, then let it go
}
}
LIBXML_NONET tells the parser never to fetch anything over the network. An uploaded XML file is untrusted input, and XML has features — external entities, recursive entity definitions — designed to make a parser read files or exhaust memory. Refuse any document type declaration outright; a data export has no need for one.
Separate analysis from action
The most useful structural decision is to split the import into two passes that never overlap.
- Analyse. Read the whole source, validate it, and write what you found into a staging table — one row per source record, with its identity, its parsed payload and a status of
pending. Nothing in the real tables changes. - Apply. Work through the pending rows, turning each into real records and updating its status.
The staging table earns its keep several times over. You can show a report before anything is changed: how many records, how many duplicates, how many unsupported. You can preview exactly what will happen to the first ten. And you never need to parse the file again, so a retry cannot be affected by the file having been moved.
Work in batches that can stop anywhere
A single request or job that processes the entire import is a single point of failure. Process a small batch at a time, and record progress per row:
$items = $import->items()->where('status', 'pending')->orderBy('id')->limit(5)->get();
foreach ($items as $item) {
try {
DB::transaction(fn () => $this->importItem($item));
} catch (Throwable $e) {
$item->update(['status' => 'failed', 'error' => $e->getMessage()]);
}
}
Each row is its own transaction. One bad record marks itself failed and the batch carries on; it does not roll back the four good ones beside it. Because progress lives in the database rather than in a variable, the import can be interrupted at any moment — a closed browser tab, a restarted server — and resumed by asking for the next pending rows.
Guard against two workers taking the same rows with a lock around the batch:
$lock = Cache::lock("import-{$import->id}", 180);
if (! $lock->get()) {
return; // another worker is on it
}
try {
$this->processBatch($import);
} finally {
$lock->release();
}
Deduplicate deliberately
Source data contains duplicates, and "the same record" is a decision, not a fact. Make the rule explicit and write down every time it is applied.
A workable order of preference:
- Exact match on a strong identifier, such as an ISBN — but only if a second field agrees, because identifiers get mistyped.
- Match on a normalised combination: title, author and publisher, with case, punctuation and spacing removed.
- Otherwise, treat the rows as different.
When two rows are judged the same, do not simply discard one. Keep the better row and let the other fill in what it is missing. A duplicate with an author where the kept row has none is worth merging.
And resist guessing. An identifier that arrives as 9.78E+12 has lost digits; it cannot be recovered by formatting. Reject the row, say why, and fix it at the source.
Report every row's fate
A summary that says "20,000 records imported" is reassuring. It is not sufficient. Sooner or later someone asks where one particular record went, and the import must be able to answer.
Give every source row exactly one outcome and a reason:
| Outcome | Meaning |
|---|---|
| Imported | A new record was created |
| Updated | An existing record was refreshed |
| Merged | Folded into another record as a duplicate |
| Skipped | Left out on purpose, with the rule that applied |
| Failed | Could not be processed, with the error |
The totals should add up to the number of source rows — every time. If they do not, a row has gone missing without explanation, and that is a bug in the import regardless of how good the data looks.
Count the gaps as well: records without a price, without an image, without a description. They imported successfully and are still not ready to publish.
Treat remote files as hostile
Imports often bring files with them — images referenced by URL. Downloading a URL taken from an uploaded file is a request made by your server to an address chosen by someone else, which is the definition of a server-side request forgery risk.
Before fetching anything:
- Accept only
httpandhttps, on the standard ports. - Resolve the host and refuse private, loopback and link-local addresses.
- Connect to the address you validated, so a second DNS answer cannot redirect the request.
- Do not follow redirects automatically; validate each hop the same way.
- Enforce a size limit while downloading, not after.
- Check the file's real type from its bytes, and store it under a name you generate.
If a file fails any check, keep the original URL on the record and mark the row as incomplete. A later retry can try again; a silently missing image cannot be found.
Dry runs and determinism
Two habits make an import much easier to trust.
A dry run does everything except write. It exercises the parser, the validation and the deduplication against the real file, and produces the report. Run it first, every time.
Determinism means the same input always produces the same output — same order, same merges, same generated slugs. Avoid anything that depends on the current time or on database ordering you did not specify. When the output is deterministic, a diff between two runs shows exactly what a change to the source file did.
The properties, in one list
- A stable identity per source record, including its origin.
- Upserts instead of inserts.
- Streaming input, flat memory.
- Analysis and application as separate passes, with a staging table between them.
- Small batches, one transaction per row, progress in the database.
- An explicit duplicate rule, applied visibly.
- One recorded outcome for every row.
- No trust in remote files.
An import built this way is not much more code than the afternoon version. The difference is that when it fails — and it will — the answer is to run it again.
