You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: context.md
+37
Original file line number
Diff line number
Diff line change
@@ -152,6 +152,43 @@ Context::when(
152
152
);
153
153
```
154
154
155
+
<aname="scoped-context"></a>
156
+
#### Scoped Context
157
+
158
+
The `scope` method provides a way to temporarily modify the context during the execution of a given callback and restore the context to its original state when the callback finishes executing. Additionally, you can pass extra data that should be merged into the context (as the second and third arguments) while the closure executes.
159
+
160
+
```php
161
+
use Illuminate\Support\Facades\Context;
162
+
use Illuminate\Support\Facades\Log;
163
+
164
+
Context::add('trace_id', 'abc-999');
165
+
Context::addHidden('user_id', 123);
166
+
167
+
Context::scope(
168
+
function () {
169
+
Context::add('action', 'adding_friend');
170
+
171
+
$userId = Context::getHidden('user_id');
172
+
173
+
Log::debug("Adding user [{$userId}] to friends list.");
174
+
// Adding user [987] to friends list. {"trace_id":"abc-999","user_name":"taylor_otwell","action":"adding_friend"}
175
+
},
176
+
data: ['user_name' => 'taylor_otwell'],
177
+
hidden: ['user_id' => 987],
178
+
);
179
+
180
+
Context::all();
181
+
// []
182
+
183
+
Context::allHidden();
184
+
// [
185
+
// 'user_id' => 123,
186
+
// ]
187
+
```
188
+
189
+
> [!WARNING]
190
+
> If an object within the context is modified inside the scoped closure, that mutation will be reflected outside of the scope.
0 commit comments