File tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed
Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Original file line number Diff line number Diff 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
You can’t perform that action at this time.
0 commit comments