Skip to content

Commit 946de37

Browse files
docs: dcoument the state sharing feature
1 parent 1242c19 commit 946de37

File tree

2 files changed

+56
-1
lines changed

2 files changed

+56
-1
lines changed

docs/.vitepress/config.mts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,8 @@ export default defineConfig({
4343
{
4444
text: 'Advanced Usage',
4545
items: [
46-
{ text: 'Extending States', link: '/extending-states' }
46+
{ text: 'Extending States', link: '/extending-states' },
47+
{ text: 'State Sharing', link: '/state-sharing' },
4748
]
4849
}
4950
],

docs/pages/state-sharing.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# State Sharing
2+
3+
State sharing lets you set a resource state once and have it automatically applied to all subsequent resources using the same state—ideal for keeping nested or related resources in sync without repeating state declarations.
4+
5+
## Enabling Shared State
6+
7+
By default, state sharing is enabled. To disable it or change the default, update your `config/stateful-resources.php`:
8+
9+
```php
10+
'shared_state' => true,
11+
```
12+
13+
::: info
14+
Disable shared state when you prefer to assign states explicitly on each resource.
15+
:::
16+
17+
## Setting a Shared State
18+
19+
When you set a state on a resource, all further resources will inherit that state unless you override it:
20+
21+
```php
22+
UserResource::state(State::Minimal)->make($user);
23+
InvoiceResource::make($invoice); // Also in the Minimal state
24+
SubscriptionResource::state(State::Full)->make($subscription); // Overrides to Full
25+
```
26+
27+
## Nested Resources Example
28+
29+
In nested resources, the shared state will be used automatically:
30+
31+
```php
32+
class UserResource extends StatefulJsonResource
33+
{
34+
public function toArray(Request $request): array
35+
{
36+
return [
37+
'id' => $this->id,
38+
'name' => $this->name,
39+
'email' => $this->email,
40+
'alias' => $this->whenStateFull($this->alias),
41+
'invoices' => $this->whenStateFull(InvoiceResource::collection($this->invoices)), // InvoiceResource automatically has the same state as UserResource
42+
];
43+
}
44+
}
45+
```
46+
47+
## ActiveState Facade
48+
You may also set the shared state explicitly through the `ActiveState` facade instead:
49+
50+
```php
51+
use Farbcode\StatefulResources\Facades\ActiveState;
52+
53+
ActiveState::setShared('minimal');
54+
```

0 commit comments

Comments
 (0)