Skip to content

Add documentation for Context::scope() #10214

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 4, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions context.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,43 @@ Context::when(
);
```

<a name="scoped-context"></a>
#### Scoped Context

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.

```php
use Illuminate\Support\Facades\Context;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

According to #10186, we prefer having PHP opening tags in the code sample blocks:

Suggested change
use Illuminate\Support\Facades\Context;
<?php
use Illuminate\Support\Facades\Context;

use Illuminate\Support\Facades\Log;

Context::add('trace_id', 'abc-999');
Context::addHidden('user_id', 123);

Context::scope(
function () {
Context::add('action', 'adding_friend');

$userId = Context::getHidden('user_id');

Log::debug("Adding user [{$userId}] to friends list.");
// Adding user [987] to friends list. {"trace_id":"abc-999","user_name":"taylor_otwell","action":"adding_friend"}
},
data: ['user_name' => 'taylor_otwell'],
hidden: ['user_id' => 987],
);

Context::all();
// []

Context::allHidden();
// [
// 'user_id' => 123,
// ]
```

> [!WARNING]
> If an object within the context is modified inside the scoped closure, that mutation will be reflected outside of the scope.

<a name="stacks"></a>
### Stacks

Expand Down