laravel-documents maintained by skyraptor
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 has its 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\DocumentPublisher;
use SkyRaptor\LaravelDocuments\DocumentGenerator;
use SkyRaptor\LaravelDocuments\Jobs\DocumentJobFactory;
$rendered = $document->render();
$generated = app(DocumentGenerator::class)->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.
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.
Each workflow invocation renders, generates, and writes at most once. Explicitly publishing the same result again can write again, and queue retries can repeat generation and publication; this is not an exactly-once queue guarantee.
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.
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.- 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.
Call withGenerator(CustomGenerator::class) on the returned job to select a
custom generator. Extend DocumentGenerator and override
protected generateContents(RenderedDocument $rendered): string to customize
the final PDF bytes while preserving generation IDs and events. 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() calls with withGenerator() and move custom
byte generation to generateContents(). 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.