Skip to content

Commit 701d69c

Browse files
Add documentation for Context::scope() (#10214)
* Update context.md * Update context.md * formatting --------- Co-authored-by: Taylor Otwell <[email protected]>
1 parent a90e202 commit 701d69c

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

context.md

+37
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,43 @@ Context::when(
152152
);
153153
```
154154

155+
<a name="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.
191+
155192
<a name="stacks"></a>
156193
### Stacks
157194

0 commit comments

Comments
 (0)