Skip to content

Commit 9eac630

Browse files
committed
Add documentation for anonymizing JSON resources
1 parent 4640c22 commit 9eac630

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

README.md

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,59 @@ public function getAnonymizedAttributes(Generator $faker): array
180180
}
181181
```
182182

183+
### Anonymizing JSON Resources
184+
185+
You can also anonymize Laravel JSON resources by implementing the `Anonymizable` interface and using the `AnonymizedResource` trait:
186+
187+
```php
188+
<?php
189+
190+
namespace App\Http\Resources;
191+
192+
use Faker\Generator;
193+
use Illuminate\Http\Request;
194+
use DirectoryTree\Anonymize\Anonymizable;
195+
use DirectoryTree\Anonymize\AnonymizedResource;
196+
use Illuminate\Http\Resources\Json\JsonResource;
197+
198+
class UserResource extends JsonResource implements Anonymizable
199+
{
200+
use AnonymizedResource;
201+
202+
public function toArray(Request $request): array
203+
{
204+
return [
205+
'id' => $this->id,
206+
'name' => $this->name,
207+
'email' => $this->email,
208+
'phone' => $this->phone,
209+
];
210+
}
211+
212+
public function getAnonymizedAttributes(Generator $faker): array
213+
{
214+
return [
215+
'name' => $faker->name(),
216+
'email' => $faker->safeEmail(),
217+
'phone' => $faker->phoneNumber(),
218+
];
219+
}
220+
}
221+
```
222+
223+
When anonymization is enabled, the resource will automatically replace sensitive data in the JSON response:
224+
225+
```php
226+
Anonymize::enable();
227+
228+
$user = User::find(1);
229+
230+
$resource = new UserResource($user);
231+
232+
// Returns anonymized data instead of original values.
233+
$response = $resource->resolve();
234+
```
235+
183236
## Testing
184237

185238
```bash

0 commit comments

Comments
 (0)