Laravel Context: The Hidden Information That Follows Your Code
When working with Laravel, we usually pass data explicitly: $user = auth () -> user (); UserExampleService :: process ( $user ); Or we add information directly to a log: Log :: info ( 'Processing order' , [ 'order_id' => $order -> id , ]); But what if you have some information that should be available throughout the current execution? For example: a trace ID the current URL a tenant ID an…
Laravel Context is a feature that allows developers to store and share information throughout the current execution of their application. This information can be anything from a trace ID and current URL to tenant ID and operation name, which may be needed by various parts of the application, such as logging and queued jobs.
To use Laravel Context, you can add data using the Context::add() method and retrieve it with Context::get(). The information is stored in the current context and can be consumed by other parts of the application without having to pass it as an argument each time.
One of the key benefits of Laravel Context is that it integrates seamlessly with application logs. By adding context information to log entries, you can create more meaningful log entries that contain both the explicitly passed information and the context data. This can be particularly useful when logging events in a queued job, as the job can still access the original trace information.
Laravel also provides hidden context for data that should not be included in logs. Hidden context is available to the application but does not appear in log entries. This allows you to store internal information that might be sensitive or unnecessary for logging purposes.
When a queued job is dispatched, Laravel captures the current context and stores it with the job's payload. This means that even if the job is executed in a separate process, it can still access the context information created during the original request. This is achieved through a process called dehydrating and hydrating, where the context is stored and then restored when the job is executed.
Laravel's queue worker has lifecycle management to ensure that context is properly cleaned up between jobs. This prevents issues where multiple jobs might share the same context, potentially leading to problems. Hidden context is stored separately and does not affect log entries, making it useful for storing internal data that should not be included in logs.
Laravel itself uses hidden context internally for tasks such as storing unique job cache store, unique job key, and unique job lock owner information when processing queued jobs. This ensures that even if a queued job encounters issues, there is enough information available to release locks and handle the situation appropriately.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.