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
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;
0 commit comments