Context
Sometimes you need to record why something happened, not just what changed. AuditChain::context() lets you attach arbitrary metadata to all subsequent audit logs — the import filename, a support ticket ID, a migration batch number.
Setting Context
use GrayMatter\AuditChain\Facades\AuditChain; AuditChain::context(['source' => 'csv_import', 'file' => 'users.csv']); // All audit logs created after this include the context User::create(['name' => 'Alice', 'email' => 'alice@example.com']); User::create(['name' => 'Bob', 'email' => 'bob@example.com']);
Both audit logs will have {"source": "csv_import", "file": "users.csv"} in their context column.
Merging Context
Calling context() multiple times merges the values:
AuditChain::context(['source' => 'api']); AuditChain::context(['request_id' => 'req-abc-123']); // Context is now: {'source': 'api', 'request_id': 'req-abc-123'}
Clearing Context
Clear the context when you are done to prevent it from leaking into unrelated operations:
AuditChain::clearContext();
A typical pattern in a controller or job:
AuditChain::context(['ticket' => 'SUP-1234']); $user->update(['email' => $newEmail]); AuditChain::clearContext();
Middleware Example
For request-level context, set it in middleware:
class AuditContextMiddleware { public function handle($request, Closure $next) { AuditChain::context([ 'request_id' => $request->header('X-Request-ID'), ]); $response = $next($request); AuditChain::clearContext(); return $response; } }
Combining with Batches
Context and batch grouping work together. The context is attached to every log entry, and the batch UUID groups them:
AuditChain::context(['reason' => 'bulk_price_update']); AuditChain::batch(function () use ($products) { foreach ($products as $product) { $product->update(['price' => $product->price * 1.1]); } }); AuditChain::clearContext();
Hash Chain Note
Like batch_uuid, context is intentionally excluded from hash computation. It is operational metadata and does not affect chain integrity.