skyraptor / laravel-documents
A document system for your Laravel application.
Fund package maintenance!
Requires
- php: ^8.3
- illuminate/support: ^12.0||^13.0
- spatie/laravel-pdf: ^2.10
Requires (Dev)
- dompdf/dompdf: ^3.1.6
- larastan/larastan: ^3.9
- laravel/pao: ^1.0
- laravel/pint: ^1.32.3
- mateffy/laravel-job-progress: ^2.2
- orchestra/testbench: ^10.0||^11.0
- pestphp/pest: ^4.6||^5.0
- pestphp/pest-plugin-laravel: ^4.1||^5.0
- pestphp/pest-plugin-type-coverage: ^4.0||^5.0
- phpstan/extension-installer: ^1.4
- phpstan/phpstan: ^2.1.32 <2.3.6
- spatie/browsershot: ^4.0||^5.0
Suggests
- mateffy/laravel-job-progress: Required to use the optional built-in job progress integration.
- skyraptor/laravel-versioned-storage: Required to keep multiple versions with VersionedDocumentStorage (requires a Unix-like runtime with PCNTL, POSIX, and sockets).
- spatie/browsershot: Required to use the Browsershot PDF driver.
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-28 19:19:15 UTC
README
Laravel Documents
A document system for your Laravel application.
Installation
composer require skyraptor/laravel-documents
The package requires spatie/laravel-pdf 2.10 or later in the 2.x series for
builder-level caching controls and PDF post-processing. Each PDF backend has its own
requirements. For Spatie's default Browsershot driver, also install
spatie/browsershot and its Node.js, Puppeteer, and Chrome prerequisites. See
the Spatie Laravel PDF documentation
for the available drivers and their requirements. Other PDF backends, versioned
storage, and progress tracking remain optional.
Publish the configuration to customize the snapshot cache:
php artisan vendor:publish --tag="laravel-documents-config"
The base package does not require database migrations. Optional versioned storage and coalesced generation have their own migration setup described below.
Usage
Define a document around the subject being rendered:
use App\Models\Invoice; use SkyRaptor\LaravelDocuments\Documents\Document; class InvoiceDocument extends Document { public static ?string $view = 'pdf.invoice'; public static ?string $disk = 'documents'; public function __construct(public Invoice $invoice) {} public function path(): string { return "invoices/{$this->invoice->getKey()}.pdf"; } public function data(): array { return ['invoice' => $this->invoice]; } }
Rendering resolves the data and Blade view immediately. It produces a readonly,
serializable RenderedDocument containing the HTML, target context, and
configuration identifiers. The PDF job receives that result, not the document
or its model:
use SkyRaptor\LaravelDocuments\Facades\Documents; $document = new InvoiceDocument($invoice); $job = Documents::makeJob($document); // Resolve data and freeze HTML now. $generationId = $job->generationId(); dispatch($job); // Generate and publish on the worker. $document->exists(); $document->get(); // Current PDF contents.
For synchronous use, generate once and publish those exact contents:
// Render once and generate final PDF bytes without storing anything: $generated = Documents::generate($document); $pdf = $generated->contents; // Publish the result without rendering or generating again: $version = Documents::publish($generated);
Alternatively, Documents::publish($document) performs all three stages in
one call.
The Documents facade resolves DocumentWorkflow, which coordinates these
document-level operations. Passing a Document renders it once; passing a
RenderedDocument skips rendering, and publishing a GeneratedDocument skips
both rendering and generation. The workflow retains no state between calls:
pass the generated result, not the original document, to reuse generated bytes.
makeJob() and makeJobIfChanged() only create jobs and never dispatch them. Pass connection:,
queue:, or job: to configure a job. By default, the document's configured job
is used, falling back to its storage configuration's default.
Prefer constructor-injecting DocumentWorkflow when desired; it exposes the
same methods as the facade. In application tests, use Laravel's facade mocking,
for example Documents::shouldReceive('generate')->once()->with($document)->andReturn($generated).
Rendered results contain HTML and generated results contain PDF bytes, which
can include sensitive data; protect serialized payloads accordingly. Jobs do
not use Laravel's SerializesModels trait.
Explicit lifecycle stages
The stage outputs are immutable and serializable:
Document -> render() -> RenderedDocument
-> generate() -> GeneratedDocument
-> publish() -> stored version (or null)
Use the focused services when coordinating stages explicitly:
use SkyRaptor\LaravelDocuments\DocumentGenerator; use SkyRaptor\LaravelDocuments\DocumentPublisher; use SkyRaptor\LaravelDocuments\Jobs\DocumentJobFactory; $rendered = $document->render(); $generated = DocumentGenerator::generate($rendered); $version = app(DocumentPublisher::class)->publish($generated);
Alternatively, queue the rendered revision instead of generating it now:
dispatch(app(DocumentJobFactory::class)->make($rendered, job: $document->job()));
DocumentGenerator accepts only rendered input and returns a GeneratedDocument
with final, post-processed contents, target, fingerprint, and generationId.
Opted-in results also carry the rendered request's snapshotId.
It does not retain the rendered HTML. DocumentPublisher accepts only that
generated result and coordinates storage, snapshot-cache updates, and publication
events; it has no generator dependency. DocumentJobFactory creates jobs from
rendered input. No service is serialized into either result or a job.
In every mode, DocumentGenerator::generate() resolves the captured generator
once from the container. Call it statically rather than resolving a generator
first; invoking it through an instance does not select that instance.
GeneratedDocument accepts caller-supplied bytes. Publication checks its
snapshot identity, but cannot verify that those bytes were produced from the
snapshot; only trusted application code should construct one directly.
Use publishWithResult() when the caller must distinguish a completed write
from a superseded attempt:
use SkyRaptor\LaravelDocuments\DocumentPublicationStatus; $result = Documents::publishWithResult($rendered); if ($result->status === DocumentPublicationStatus::Superseded) { abort(409, 'The requested PDF was superseded. Please try again.'); } $version = $result->version; // null for unversioned storage
Documents::publishWithResult() accepts the same inputs and generationId as
publish(). DocumentPublisher::publishWithResult() accepts a generated result.
The result reports Published with the storage version (which may be null), or
Superseded with a null version. Generation, storage, and cache failures still
throw. The existing publish() return value is unchanged: null can mean either
an unversioned write or a superseded attempt.
An outcome describes that publication attempt, not a guarantee that its target remains unchanged afterward. Applications are responsible for deciding how to respond and for any availability or freshness checks needed before serving it.
Each workflow invocation renders, generates, and writes at most once. Outside coalescing, explicitly publishing the same result again can write again, and queue retries can repeat generation and publication. Coalescing reuses an existing matching PDF when possible, but is not an exactly-once queue guarantee.
Document metadata
Override metadata() to freeze PDF metadata alongside the rendered HTML:
use SkyRaptor\LaravelDocuments\DocumentMetadata; public function metadata(): ?DocumentMetadata { return new DocumentMetadata( title: 'Invoice '.$this->invoice->number, author: 'Accounts', creationDate: $this->invoice->created_at, ); }
The immutable metadata supports title, author, subject, keywords,
creator, and creationDate (a PDF date string or DateTimeInterface). It
travels with the snapshot, participates in its fingerprint, and replaces all
metadata set by the builder callback. Return null to leave existing builder
metadata unchanged; metadata configured only in that callback is resolved at
generation time and is not part of the snapshot fingerprint. Move
document-specific metadata into metadata() for change detection. Metadata
can contain sensitive information and must be protected like rendered HTML.
PDF driver configurations
The default PDF configuration resolves Spatie's PdfDriver from the Laravel
container when generation runs. Configure Spatie's default driver or register
additional named configurations in a service provider that runs in every
application and worker:
use SkyRaptor\LaravelDocuments\Pdf\DocumentPdfDriverManager; use Spatie\Browsershot\Browsershot; use Spatie\LaravelPdf\Drivers\BrowsershotDriver; use Spatie\LaravelPdf\PdfBuilder; app(DocumentPdfDriverManager::class)->register( 'invoice-v1', fn () => (new BrowsershotDriver(config('laravel-pdf.browsershot', []))) ->customizeBrowsershot( fn (Browsershot $browser) => $browser ->waitUntilNetworkIdle() ->setOption('preferCSSPageSize', true), ), function (PdfBuilder $builder): void { $builder ->format('A4') ->meta(title: 'Invoice', author: 'Accounts'); }, );
Select it with public static string $pdfDriver = 'invoice-v1'; on the
document. A factory can instead return any Spatie PdfDriver, including a
custom implementation; the optional third argument configures a fresh Spatie
PdfBuilder. Use its methods for page settings, metadata, encryption, or
Browsershot customization. Margins default to zero and can also be changed there.
Browsershot drivers are cloned for generation so builder settings do not leak
into shared driver instances; factory-configured defaults are preserved.
Generation calls generatePdfContent(), so metadata and encryption are applied
before the final bytes are returned or passed to document storage. Encryption
requires Spatie's optional encryption dependencies. Post-processing failures
propagate and prevent storage of an unprocessed PDF.
The snapshot supplies the body HTML. Builder callbacks must not load the
document's data or render views; view(), headerView(), and footerView()
are rejected. Use previously rendered HTML for any headers or footers.
Spatie's PDF cache is disabled by default; a callback can explicitly enable it
with cache(). Automatic cache fingerprints include the registered configuration
identifier as well as Spatie's HTML and builder settings. Explicit cache keys
are used unchanged; make them unique across configurations unless sharing
cached output is intentional.
Only the identifier is serialized. The worker resolves its own factory and builder configuration, so all processes must register the identifiers they use. Different deployments may produce different results for the same snapshot if their configuration changes. Use a new identifier when a configuration change should also count as a snapshot change.
Storage
The built-in disk configuration uses DiskDocumentStorage: it writes to the
document's resolved disk and path, replaces the existing file, and selects a
unique job per target. The built-in versioned configuration selects
VersionedDocumentStorage and a non-unique job. Install its optional dependency
and migrations before using it:
composer require skyraptor/laravel-versioned-storage:0.2.0-beta.1
php artisan vendor:publish --tag="laravel-versioned-storage-migrations"
php artisan migrate
Version 0.2.0-beta.1 is a pre-release tested with this package. It requires a
Unix-like runtime with PCNTL, POSIX, and sockets; native Windows PHP is not
supported. See its installation guide.
Set public static string $storage = 'versioned'; on the document, then use
$document->versions() and $document->get($version) to read published
versions. The current version is the last successfully published version,
not necessarily the last dispatched or the last completed job.
Storage configurations are registered in the container, not on individual documents. For example, register a second disk configuration:
use SkyRaptor\LaravelDocuments\Storage\DiskDocumentStorage; use SkyRaptor\LaravelDocuments\Storage\DocumentStorageManager; app(DocumentStorageManager::class)->register( 'long-write-disk', fn () => new DiskDocumentStorage(lockTimeout: 45), );
Select it with public static string $storage = 'long-write-disk';. The
optional third registration argument is the default job class. Use a job whose
uniqueness and batch behavior match the storage's write guarantees.
For a database or other backend, implement the DocumentStorage contract and
register its factory in the same manager. Provide its serializable target
parameters with a readonly DocumentStorageContext subclass, and override the
document's storageContext():
use SkyRaptor\LaravelDocuments\Documents\Document; use SkyRaptor\LaravelDocuments\Storage\Contexts\DocumentStorageContext; final readonly class InvoiceRecordContext extends DocumentStorageContext { public function __construct(public int|string $invoiceId) {} public function identity(): string { return 'invoice-record:'.$this->invoiceId; } } class StoredInvoiceDocument extends Document { public static ?string $view = 'pdf.invoice'; public static string $storage = 'invoice-records'; public function __construct(public int|string $invoiceId) {} public function data(): array { return ['invoiceId' => $this->invoiceId]; } public function storageContext(): DocumentStorageContext { return new InvoiceRecordContext($this->invoiceId); } }
The context identity must be stable and unambiguous across all storage
configurations that may address the same target: it is used for unique jobs and
snapshot-cache locks. Contexts must contain immutable, serializable values, not
models, closures, connections, or storage instances. The built-in
FilesystemDocumentStorageContext contains the resolved disk name and a
Flysystem-normalized path. Different disk names pointing to the same physical
location are still distinct identities; use one disk name consistently.
Storage and driver factories are resolved separately in the worker.
Skipping unchanged snapshots
use SkyRaptor\LaravelDocuments\Facades\Documents; if ($job = Documents::makeJobIfChanged($document)) { dispatch($job); }
Documents::makeJobIfChanged() renders the document (or accepts an existing
RenderedDocument) and compares it with the last
successfully cached snapshot for the target. The comparison uses rendered HTML, target
context, and configuration identifiers, not PDF bytes. They do not detect a
deleted or externally modified PDF, changed external assets, or different
driver/storage settings under the same identifier. Use versioned asset URLs or
embed assets, change the relevant identifier when configuration changes, and use
Documents::makeJob() for a forced regeneration. Cache eviction also causes
regeneration. For an existing snapshot, use
DocumentSnapshotCache::changed($rendered) or
DocumentJobFactory::makeIfChanged($rendered).
The snapshot cache defaults to Laravel's default cache store. Configure
snapshot_cache.store in the published laravel-documents.php config to select
another store. All publishers must use the same persistent, shared cache and
prefix, with atomic lock support; array is suitable only for a single process
and the null store is rejected. Set snapshot_cache.lock_seconds longer than
the worst-case storage write and snapshot_cache.lock_wait_seconds to an
appropriate contention timeout. Defaults are 300 and 30 seconds, respectively.
Partial configuration overrides retain defaults for omitted nested settings.
Unique-job locks and disk-storage write locks use Laravel's default cache store;
it must also support atomic locks and be shared across processes.
Unique-lock operations follow the active default store after cache switches or
driver purges in long-lived processes. Configure the same store and prefix for
dispatch and worker execution, before job deserialization, and keep that context
through cleanup. Switching stores does not migrate locks already held.
The lock serializes each target's storage publication and snapshot-cache update;
PDF generation itself can run concurrently. A failed storage write invalidates
the previous cached snapshot so a later comparison will regenerate. If caching
or releasing the lock fails after a successful storage write, the error is
reported rather than retrying the published job. Lock-release failures include
both exceptions and false results; they do not replace an original storage
exception, and locks are never force-released. The comparison and subsequent
dispatch are not atomic: simultaneous callers or already-running jobs can still
produce additional versions. External storage writes do not participate in this
coordination. A worker crash after storage can also cause a retry.
Latest rendered snapshot wins (opt-in)
This section describes the default cache-backed policy. For database-backed ordering with coalesced queued work, see Coalesced generation below.
Prevent an older queued snapshot from overwriting a newer synchronous HTTP publication by enabling this policy on the document:
public static ?bool $latestSnapshotWins = true;
Alternatively, set 'latest_snapshot_wins' => true in the published
config/laravel-documents.php to enable it package-wide. The document property
defaults to null (inherit); false explicitly opts out. Override
latestSnapshotWins(): ?bool for instance-specific selection. Explicitly
constructed snapshots accept new RenderedDocument($html, $target, latestSnapshotWins: true) and otherwise inherit the package default.
After HTML rendering succeeds, snapshot construction registers a new opaque
snapshotId in the shared snapshot cache under the target's publication lock.
This registration defines rendering completion and ordering; it does not use
worker timestamps or PDF generation completion. Snapshots with the same current
fingerprint share an ID and remain eligible to publish. A different fingerprint
supersedes earlier opted-in snapshots for that storage-context identity. If the
content changes from A to B and back to A, the new A gets a new ID and the
original A remains superseded. Snapshot IDs do not affect content fingerprints.
When a freshness check must not replace a revision registered while source data
is being loaded, use DocumentSnapshotCache::captureIfUnchanged($target, $load).
The closure must load a fresh document for the same target with latest-snapshot
ordering enabled. The method observes the current marker before invoking the
closure, then conditionally registers under the publication lock. It returns
null if another revision was registered in between; the caller can retry or
return a conflict. An equivalent current snapshot retains its existing ID.
This cache-backed API uses the same shared snapshot cache and lock requirements
as ordinary ordered publication. For coalesced generation use the separate
DocumentCoalescer::captureIfUnchanged() API described below.
For ordered cache-backed snapshots, DocumentSnapshotCache::existingPublicationStatus($snapshot)
checks the latest marker, published fingerprint and storage existence under the
publication lock without generating a PDF. It returns DocumentPublicationStatus::Published
for a matching file, DocumentPublicationStatus::Superseded if another snapshot is current, or null if
publication is needed. The check cannot prevent changes after the lock is released;
in particular, a later fixed-path download may observe a subsequent publication.
For fixed-path downloads, DocumentSnapshotCache::readPublished($snapshot)
checks ordering and the published fingerprint and reads the bytes under the
publication lock. It returns null when the snapshot is superseded or its
publication is missing, and propagates storage read errors. Serve the returned
bytes directly instead of redirecting to a path another publisher can replace.
The immutable ID survives serialization and is copied into GeneratedDocument.
Generation, job creation from existing snapshots, publication, and retries do
not register the snapshot again. Under the same target lock, publication checks
the ID before writing or changing the stored fingerprint. Superseded results
write nothing, emit DocumentSuperseded instead of DocumentStored, and return
null from publish() or a Superseded result from publishWithResult();
generation may still have run. The event includes target,
generationId, snapshotId, and latestSnapshotId. Its listeners run after
the lock is released. A built-in job's generated() is true after the completed
attempt, including a superseded one; it is not proof of storage.
The newest distinct rendered fingerprint wins even if its job is never dispatched, is cancelled, or fails generation. Superseded results do not become eligible again. Repeated publication of the latest result is still allowed. The policy applies to disk, versioned, and custom storage through the common publication service; superseded results do not create historical versions.
Queue uniqueness is unchanged: GenerateUniqueDocument still discards
duplicate dispatches. Rendering a different snapshot can supersede an older job
even if Laravel subsequently discards the newer job; an equivalent snapshot
does not. If every newer request
must be queued, select GenerateVersionedDocument (also usable with disk
storage), a non-unique custom job, or its progress-enabled equivalent.
This policy prevents stale writes; it does not schedule replacement jobs.
Equivalent snapshots may publish in either order. The fingerprint covers rendered
HTML, document metadata, target, and driver identifier, not mutable external
assets, builder-only metadata, or changes to a driver's implementation.
Rendering now needs the shared persistent cache when opted in, even for generation without publication. All participating HTTP processes and workers must use the same cache store and prefix, and opt in consistently. Untracked snapshots, including explicitly opted-out and legacy payloads, retain the old publication-order behavior. Registration failures propagate. Missing or evicted latest-request markers fail publication explicitly rather than allowing stale contents through; render a fresh snapshot to recover. Do not flush or change the coordinating cache while workloads are outstanding. Atomic-lock lease duration must exceed storage writes; external writes and expired lock leases are outside the guarantee.
During a rolling upgrade, older processes still register a new ID for every render, including equivalent renders. Existing UUID-only markers cannot be matched to a fingerprint, so the first new registration supersedes them. Restart all rendering processes to obtain the equivalent-snapshot behavior consistently.
Coalesced generation (opt-in)
Coalescing keeps the newest pending rendered snapshot per target. One queue
wakeup normally processes it; a request arriving during generation replaces the
pending snapshot and the worker continues with the newest one. Intermediate
snapshots may be skipped. This mode currently requires the built-in versioned
storage and skyraptor/laravel-versioned-storage 0.2.0-beta.1 or a compatible
version. Install and migrate that package first, then publish and run the
Documents migration:
php artisan vendor:publish --tag=laravel-documents-migrations php artisan migrate
Set latest_snapshot_wins and coalescing.enabled to true in
config/laravel-documents.php. Set coalescing.connection and
laravel-versioned-storage.connection to the same Laravel database connection
(both default to the default connection), and run both packages' migrations on
that connection. Every document rendered while coalescing is enabled must use
versioned storage and latest-snapshot ordering. Calls starting inside a database
transaction are rejected: enqueue after the caller's transaction commits.
use SkyRaptor\LaravelDocuments\Facades\Documents; use Illuminate\Support\Facades\Schedule; // InvoiceDocument has public static string $storage = 'versioned'. $snapshot = $document->render(); Documents::dispatchCoalesced($snapshot, connection: 'redis', queue: 'pdf'); // Schedule the recovery command in the application's console routes: Schedule::command('documents:recover')->everyMinute(); Schedule::command('laravel-versioned-storage:cleanup')->everyMinute();
dispatchCoalesced() returns false if that rendered snapshot was already
superseded before it could be recorded, or true when it was accepted.
Dispatch errors throw even though the recorded request remains recoverable.
For optional target feedback, publish and run the target-events migration on the
coalescing connection, then enable coalescing.record_target_events in every
worker and scheduler. Documents::targetEventCursor($target) returns the
current cursor; Documents::targetEvents($target, $cursor) returns later
events in order. AttemptFailed records an exception observed by a coalesced
job while its target remains pending. RecoveryDelayed records recovery of an
expired lease, which can reflect queue delay or a still-running worker, not
proof of failure. Neither represents a terminal target state.
Events are retained until the application removes them; do not prune events while subscribers still need them. A terminated worker cannot record its own death, and a database outage can prevent recording an observed failure. A recording error is reported without replacing the original job exception. If recording a recovery event fails, the error is reported and recovery retries the reservation without that event; failures to reserve or dispatch work still surface. Recovery can later record uncertainty after the database is available. Event history and notifications are not exactly-once. Applications must authorize access to each target before reading its state or history.
Dispatch accepts only a RenderedDocument. Rendering registers its ordering
marker and pending snapshot together in one database transaction. If the caller
crashes after that commit but before dispatch, the scheduler recovers the latest
snapshot; a crash before the commit leaves the previous state intact. Rendering
therefore requests eventual stored-PDF generation even when dispatch is never
called. Dispatch requests an immediate wakeup; the queue job contains only its
target key and worker token, and the worker reads the immutable snapshot from
the database.
Generation and coalesced recovery resolve the generator class captured in the snapshot. To
use a custom generator, override Document::generator() to return its class
name, or pass generator: CustomGenerator::class when constructing a
RenderedDocument. Only the class-name string is stored; no generator instance
is serialized. The class and its dependencies must be available to every worker.
It participates in the snapshot fingerprint. Jobs always use the captured
class; configure the generator on the document or snapshot rather than on
the job. Keep container bindings consistent
across renderers and workers, including bindings for the default DocumentGenerator.
Work recovered before any explicit dispatch uses the default queue connection and queue. A new snapshot rendered while work is pending inherits that work's queue settings. If recovery starts before a dispatch specifying another queue, the existing wakeup may already be on the previous or default queue.
Submit the snapshot even if a separate change check says its fingerprint matches: that check and dispatch are not atomic, and other snapshots may be registered between them. The worker checks for an existing matching PDF and skips generation when it can; publication still fences superseded snapshots.
Run Laravel's scheduler and queue workers continuously. The durable target row
is written before dispatch. If dispatch fails, the exception is raised and
recovery retries after coalescing.lease_seconds. Terminal worker failures,
crashes, and lost wakeups are also recovered; monitor failed jobs and command
errors. Recovery attempts other targets and abandoned stages when one fails,
reports additional failures, and rethrows the first failure so the command
does not report success. Choose a lease longer than normal queue delay and processing time to
avoid unnecessary duplicate attempts, and set the queue worker timeout below
its queue's retry/visibility timeout. Recovery can dispatch another worker after
a lease expires, so generation and wakeups are at least once, not exactly
once. Recovery keeps existing wakeups valid even when queue delay exceeds the
lease; overlapping workers can consequently process the same snapshot.
Queue connection and name for recovery follow the latest pending request.
Coalesced jobs do not implement the optional progress integration or batches.
Also schedule Versioned Storage's cleanup command: it reclaims interrupted
uploads that crashed before the document stage journal was recorded, as well
as retired versions. Its own upload deadlines and cleanup grace apply.
Synchronous publishWithResult() uses the same database ordering and staged
publication, but rendering its snapshot also records recoverable queue work.
The scheduler can run a worker concurrently with synchronous generation, so
duplicate generation is possible. The first matching publication wins: later
attempts discard their staged PDF and return the existing version, even if the
generated PDF bytes differ. They do not emit DocumentStored again. If the
existing PDF is missing, a new attempt publishes a replacement. File existence
is checked while holding the target's database lock, so a slow storage check
can delay other operations for that target.
Successful synchronous publication or reuse clears matching pending work
atomically; it does not clear a newer snapshot.
For HTML-only previews, use $document->html() instead of render(); authorize
any application route serving that HTML. A newer synchronous publication
supersedes older pending work; if the same snapshot is already current and the
PDF exists, the worker skips generation. Conversely, a newer queued snapshot
supersedes an older synchronous attempt. Registration order is defined after
rendering, not by source-record revision or the time a request started.
For synchronous generation that may reuse an unchanged PDF, call
Documents::publishIfChanged($document) (or pass an ordered
RenderedDocument). It returns a DocumentPublicationResult: an existing
version is reused only when its fingerprint matches and its file exists;
otherwise it generates and publishes normally. If a newer snapshot is
registered during the check, it returns Superseded. Reuse requires
coalescing and versioned storage, and must run outside a database transaction.
Reuse does not emit a new DocumentStored event. Versions published before the reuse migration are
regenerated once because their version identifier was not recorded.
Documents::targetStatus($document->target()) exposes shared target state:
NotScheduled, Pending, Published, or Tombstoned from
DocumentTargetStatus. Pending includes queued, running, failed-attempt,
and recovery-waiting work, including snapshots rendered but not explicitly
dispatched; it is not a percentage or a terminal failure. A successful
synchronous publication or reuse reports Published without a worker.
Published means the latest fingerprint was published, not that the physical
file has been checked at query time. This state is shared by all requests for
that target, not attached to any individual job or requester.
For background freshness checks, DocumentCoalescer::captureIfUnchanged($target, $load) observes the target before invoking the document-loading closure. It
returns null if another snapshot was registered or the target was retired
before capture completes. Load fresh source data inside the closure. A matching
file published before the target is locked is reused without creating pending
work; otherwise the returned snapshot is durable pending work and can be
dispatched or recovered. Checking a matching file holds the target and versioned
storage locks until the filesystem existence check completes.
publishedVersion($snapshot) and isCurrent($snapshot) inspect the target without
clearing pending work. Recheck after reading a version: these observations do
not reserve it or prevent subsequent publication or retirement.
Versioned writes are staged outside a transaction. The target's latest snapshot
check, current-version switch, and fingerprint update commit together on the
same database connection. An ID is journaled before a stage can become ready;
recovery discards abandoned stages after coalescing.stage_retention_seconds.
Set this retention longer than the longest expected staging operation. Recovery
may invalidate a slow stage, causing its publisher to fail and require a retry.
Versioned Storage's upload deadlines, cleanup grace, filesystem and database
failure limitations also apply. External writers and older application versions
that bypass this protocol are not fenced: drain old workers and deploy the mode
consistently before enabling it. Disabling or changing the database while work
is outstanding also breaks coordination.
Pending rendered snapshots are encrypted with Laravel's application encryption key until work completes. All renderers, workers, and recovery processes must share the same key. Configure Laravel's previous keys when rotating it and retain them until all pending snapshots encrypted with those keys have finished; losing the key causes explicit decryption failures and prevents recovery. Existing plaintext pending rows remain readable for upgrades, and old backups, replicas, logs, or failed-job records may retain plaintext. Encryption does not hide target metadata, fingerprints, or stored PDFs; restrict access and apply appropriate retention policies.
Older package versions cannot read newly encrypted rows. Before upgrading, pause rendering, workers, and recovery, deploy the new version everywhere, and restart processes before resuming. Do not roll back while encrypted pending rows remain. Workers must also understand document metadata before receiving snapshots that contain it; drain old workers before enabling document-level metadata. Target ordering rows and fingerprints remain after completion to keep old snapshots fenced; do not delete them while old work or snapshots may exist. Only trusted processes should be allowed to modify these tables.
Before deleting a document's underlying record, the application can fence existing and future registrations:
Documents::tombstoneTarget($document->target()); // To deliberately allow new work for this target later: Documents::restoreTarget($document->target());
When using a Laravel Versioned Storage version with resource retirement support,
Documents::retireTarget($target) also hides all published versions and schedules
their physical deletion through Versioned Storage cleanup. Fencing and retirement
commit together on the shared database connection. Previously issued direct URLs
may remain usable until cleanup removes the files.
Tombstoning supersedes existing snapshots, clears pending work, and rejects new
registrations until an explicit restore. Previously captured snapshots remain
superseded after restoration. These operations may run inside the same
Laravel-managed transaction as the record deletion or restoration when both
use the same database connection; a rollback restores the previous state.
Neither operation physically deletes published PDFs or prevents writers that
bypass this protocol. Documents::invalidate($target) remains available when
only existing snapshots should be superseded without blocking new registrations;
it does not clear an existing tombstone.
Document events
Generation and publication emit the existing lifecycle events:
DocumentGeneratoremitsDocumentRenderingbefore PDF generation, including when usinggenerate()without publishing. This event name refers to PDF generation, not rendering the Blade view.DocumentPublisheremitsDocumentStoredafter storage succeeds, with the version identifier ornull. It never emits a generation-start event.- With latest-snapshot-wins enabled, superseded publication emits
DocumentSupersededwithout storing or emittingDocumentStored. - Either stage emits
DocumentRenderFailedif it throws, with the exception class and message; the original exception is rethrown.
The events in SkyRaptor\LaravelDocuments\Events expose target and
generationId, not the snapshot HTML. The target contains the storage
identifier and context, not a storage service. Contexts and failure messages
can still contain sensitive information. A failed attempt can leave partial
files and can later be retried.
The generation ID is created with the job and survives queue serialization and
retries. Direct generation creates a new ID unless
generate($rendered, generationId: $id) supplies one explicitly. The generated
result owns that ID; publication preserves it. At the document level, use
Documents::generate($document, generationId: $id) or
Documents::publish($document, generationId: $id). An existing generated
result's ID cannot be overridden.
A duplicate unique job is discarded and emits no events for its ID. Listener
exceptions are reported to Laravel and do not alter the storage result; Laravel
may stop invoking later listeners. Use asynchronous queued listeners when they
need independent retries. Event delivery is best-effort, not crash-proof.
Jobs, progress, and batches
Documents::makeJob() and makeJobIfChanged() choose the explicit job: argument,
then the document's configured job, then the storage configuration's default.
They also accept connection: and queue: arguments.
Built-in jobs preserve their existing connection and queue when the corresponding
argument is omitted or null; non-null arguments override only that setting.
The lower-level DocumentJobFactory::make() accepts a snapshot instead; pass
job: $document->job() to preserve the document's job setting when using it
directly.
Select a custom generator before rendering by overriding Document::generator()
or passing generator: to RenderedDocument. Extend DocumentGenerator and override
protected generateContents(RenderedDocument $rendered): string to customize
the final PDF bytes while preserving generation IDs and events. The generate()
entry point is final and cannot be overridden. Constructor
dependencies are resolved from the worker's container. Jobs generate once per
execution and pass that result to DocumentPublisher.
Jobs implement
Jobs\Contracts\GenerateDocument. Usually extend GenerateUniqueDocument for
unversioned storage or GenerateVersionedDocument for versioned storage, so
their uniqueness and batch rules are retained. The base jobs expose generate(),
generated(), and version() to custom handlers and middleware. A job running
on a worker does not update the original dispatching-side object.
Optional Mateffy Job Progress integration
Install the optional progress package:
composer require mateffy/laravel-job-progress:^2.2
Select one of the built-in jobs:
use SkyRaptor\LaravelDocuments\Integrations\JobProgress\GenerateUniqueDocumentWithProgress; use SkyRaptor\LaravelDocuments\Integrations\JobProgress\GenerateVersionedDocumentWithProgress; // For disk storage: public static ?string $job = GenerateUniqueDocumentWithProgress::class; // For versioned storage instead: public static string $storage = 'versioned'; public static ?string $job = GenerateVersionedDocumentWithProgress::class;
Save $job->generationId() before dispatch; later query
GenerateUniqueDocumentWithProgress::getProgress($id) or
GenerateVersionedDocumentWithProgress::getProgress($id) as appropriate.
Query the concrete job class when using a subclass. Progress can be null until
the job starts. On completion, its result is the version identifier or null
for unversioned storage. The integration does not provide intermediate
PDF-render percentages. Protect progress lookups; failure messages may contain
sensitive details.
The built-in jobs support individual cancellation before rendering; versioned
jobs also check batch cancellation. Cancellation is cooperative and cannot stop a
render already in progress. The integration uses Mateffy's progress error
handling unchanged. Progress failures can fail the job even after the PDF was
stored; queue retries may overwrite it or publish another version. For customization,
see TrackedVersionedDocument. If
subclassing a tracked job, add Mateffy's #[Cancellable] attribute again to the
concrete subclass to enable cancellation.
The contract and generate() also allow integrations with other progress
packages without depending on Mateffy. A custom job that implements the contract
without extending the base jobs may reuse TracksDocumentProgress; it must also
implement HasJobProgress and provide documentBatchCancelled(): bool.
Custom job and generator classes used on queues must be named and autoloadable by
every worker.
Batches
Only batch non-unique jobs with storage that permits multiple writes, such as
GenerateVersionedDocumentWithProgress with versioned storage. Configure
Laravel's batch table and workers
and use an asynchronous queue: the database batch repository executes sync
jobs inside a transaction, which versioned storage rejects.
Laravel batch progress counts successful jobs, including cancelled jobs that return normally; failed jobs are tracked separately and individual percentages are not aggregated. Store both the batch ID and each generation ID when both kinds of progress are needed.
GenerateUniqueDocument and its tracked subclass reject batching because
Laravel does not acquire unique locks for batched jobs. Dispatch them
individually; unique locks are shared across subclasses for the same target.
Custom unique jobs using Laravel's SerializesModels also release that shared
lock when Laravel deletes or fails the job because a related model is missing.
The model must not be part of the frozen document input.
Upgrading from the previous API
Unique jobs now expose a hash of the storage-context identity through uniqueId(),
while retaining the same underlying target lock
keys. Drain old unique-job payloads before deploying this change: their saved
missing-model cleanup metadata cannot be repaired retroactively. Locks already
leaked by missing-model cleanup need to be removed manually.
The skeleton-only LaravelDocuments service and facade, placeholder command,
translation, and migration were removed. Previously published copies and any
placeholder table remain in applications until explicitly removed.
This architecture changes the snapshot, target, storage, and job contracts.
Drain or replace queued jobs created with the old serialized payload before
deploying. Replace storage class properties with registered identifiers and
move storage options to manager registrations. Existing disk .hash sidecars
and versioned document.hash files are left untouched; old version directories
remain readable, but change detection now starts from the shared snapshot cache.
Document::renderer() and DocumentRendererHandler were removed. Use the
Facades\Documents facade or inject DocumentWorkflow for document-level
generation, publication, and job creation. For explicit revision control, capture
RenderedDocument once with Document::render() (formerly snapshot()).
DocumentSnapshot is now RenderedDocument, and DocumentRenderer is now
DocumentGenerator. Generation returns GeneratedDocument instead of a string;
read PDF bytes from contents and pass that result to DocumentPublisher::publish()
or Documents::publish(). Publication no longer accepts rendered input at the
low level or regenerates PDF bytes. DocumentJobFactory and
DocumentSnapshotCache::changed() still consume rendered input.
Replace job withRenderer(), withGenerator(), and generator overrides with a
generator selected on the document or rendered snapshot, and move custom byte
generation to generateContents(). The job generator hook and
withGenerator() are no longer used.
Generation IDs are generation arguments
and are carried by the generated result, not mutable generator state.
The snapshot_cache configuration and existing event class names are unchanged.
The default PDF driver now uses Spatie's configured driver and does not apply
the former hard-coded Browsershot flags, network-idle wait, or Sail/production
sandbox overrides. The builder-level PDF cache is disabled by default. Driver
registration callbacks now receive PdfBuilder rather than PdfOptions;
replace property assignments with builder methods such as format('A4').
Register an explicit driver configuration when those behaviors are required, and review the
security implications before disabling browser security features.
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Thank you for considering contributing to Laravel Documents! Please review our contributing guide to get started.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
License
Laravel Documents is licensed under the AGPL-3.0-only with the Library Integration Exception. Independent applications may retain their own license, including proprietary terms; the package and covered modifications remain subject to AGPL obligations. See COPYING for the full license.