Export Laravel Form Submissions Safely to CSV, Excel, and PDF
Export Laravel Form Submissions Safely to CSV, Excel, and PDF
An export is not a formatting feature. It is a privileged bulk release of personal data that may execute spreadsheet formulas, exhaust memory, expose another tenant, or remain downloadable long after the source records expire.
Design CSV, Excel, and PDF as separate output contracts around one authorized export query.
Authorize the operation, query, and artifact
Use a dedicated policy for export; permission to view one submission does not automatically grant bulk download. Resolve the tenant/form inside the authorized service and build the query from that scope. Never accept a raw model class, table, selected columns, or filesystem path from the request.
Record who requested the export, which form/version/filter it covered, row count, purpose/reason where required, and artifact expiry. Keep answer values out of routine audit logs.
Render historical labels correctly
Dynamic fields change. An old submission should use its immutable form revision (and locale) to resolve columns and labels. Otherwise a deleted field disappears, renamed labels rewrite history, and option IDs become unreadable.
Choose the layout:
- one combined export with stable field codes and a label map;
- one sheet/file per form revision;
- a normalized row-per-answer format for heterogeneous schemas.
Wide “one column per field” CSVs are convenient for a single revision. A normalized format is safer across many revisions and repeaters. Document the contract so downstream imports do not depend on accidental column order.
Defend against CSV formula injection
Spreadsheet programs may treat cells beginning with =, +, -, @, tabs, or line-control tricks as formulas. Quoting a CSV field does not necessarily stop formula evaluation after import.
There is no universal neutralization that works for every spreadsheet and preserves every downstream use. Define a policy such as prefixing dangerous cells with an apostrophe for human spreadsheet use, or exporting a typed XLSX format with text cells. Offer a raw machine export only to trusted technical users with an explicit warning and separate ability.
Test leading whitespace, tabs/newlines, separators, quotes, and each formula marker. Review OWASP CSV injection.
CSV, Excel, and PDF serve different jobs
| Format | Best for | Main risks |
|---|---|---|
| CSV | Portable machine/human rows | Formula injection, encoding, type loss |
| XLSX | Typed cells, sheets, formatting | Library memory, formulas, hidden metadata |
| Human-readable snapshot | Layout overflow, font/language, not analysis-ready |
Do not call PDF archival merely because it looks fixed. Long-term archival may require a specific PDF standard, embedded fonts, metadata policy, and verification outside a normal HTML-to-PDF job.
Stream or queue large exports
Avoid loading all submissions and relationships into memory. Iterate in stable chunks or use lazy cursors where ordering and relation access are safe. Eager-load the revision/form data needed for each batch and measure query count.
For modest CSV responses, stream to the authorized requester. For large/expensive XLSX/PDF jobs:
- create an export record;
- queue generation after commit;
- write to private storage with a generated name;
- mark completion/failure;
- notify the requester without attaching sensitive data;
- serve through an authorized short-lived download;
- delete on expiry.
Prevent overlapping duplicate jobs or make generation idempotent. Bound filters and output size so an authorized user cannot accidentally exhaust the worker fleet.
Apply field-level redaction
Some roles may export ordinary answers but not IDs, health data, uploaded documents, internal notes, IP/security metadata, or secrets. Define exportable fields by policy/classification rather than “all JSON keys.”
Avoid placing raw upload URLs in files. A permanent public URL bypasses later authorization and retention. Export a controlled reference, filename, or short-lived link only when the recipient is allowed.
Handle locale and encoding
Use UTF-8 consistently and decide whether a BOM is needed for target spreadsheet software. Preserve line breaks intentionally. In PDF, embed fonts that cover all scripts, set lang/direction correctly, and test right-to-left content.
Dates should include timezone or be rendered with a documented export timezone. Avoid spreadsheet auto-format surprises for long numeric identifiers, postal codes, and values beginning with zero—write them as text when semantics require it.
Retain exports for less time, not more
An export duplicates the source data and is usually less controlled after download. Give server-side artifacts a short expiry, clean them even if the user never downloads, and include them in rights/incident workflows. The GDPR retention guide explains why deleting only database rows is incomplete.
Failure tests
- a user cannot export another tenant/form;
- restricted roles receive redacted columns;
- historical revisions preserve labels and deleted fields;
- formula payloads follow the documented policy;
- quotes, separators, newlines, Unicode, RTL, and leading zeros round-trip;
- large jobs stay within a memory/query budget;
- generated artifacts are private and expire;
- a signed URL cannot outlive authorization policy unnoticed;
- partial generation does not expose a corrupt file;
- audit records contain scope/outcome but no answers.
Exports are trustworthy when the same care applied to collecting a submission survives its most portable copy. Start with authorization and historical semantics; choose the file format only after those rules are clear.