From 7d16c48d2712690cafd6bf245a9a5c3e65a77f0a Mon Sep 17 00:00:00 2001 From: achraf Date: Tue, 26 Aug 2025 22:19:15 +0100 Subject: [PATCH] add $forcewrapping documentation --- eloquent-resources.md | 71 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/eloquent-resources.md b/eloquent-resources.md index f2e0b55501c..36c57f672df 100644 --- a/eloquent-resources.md +++ b/eloquent-resources.md @@ -428,6 +428,77 @@ class AppServiceProvider extends ServiceProvider > [!WARNING] > The `withoutWrapping` method only affects the outermost response and will not remove `data` keys that you manually add to your own resource collections. + +#### Force Wrapping + +In some cases, you may want to ensure that your resource response is always wrapped in the configured wrapper key, even when the resource data already contains that key. This commonly occurs when working with model attributes that match the wrapper name (usually `data`). + +By default, if your resource array contains a key that matches the wrapper, Laravel will skip the wrapping to avoid double-wrapping. However, this can lead to inconsistent API responses depending on your model's structure. + +To force consistent wrapping behavior, you may set the `$forceWrapping` static property to `true` on your resource class: + +```php + + */ + public function toArray(Request $request): array + { + return [ + 'id' => $this->id, + 'title' => $this->title, + 'data' => $this->data, // This won't prevent wrapping anymore + ]; + } +} +``` + +With `$forceWrapping` set to `true`, your response will be consistently wrapped regardless of the model's attributes: + +```json +{ + "data": { + "id": 1, + "title": "Task Title", + "data": "some model data" + } +} +``` + +Without `$forceWrapping`, the same resource might return an inconsistent response structure: + +```json +{ + "id": 1, + "title": "Task Title", + "data": "some model data" +} +``` + #### Wrapping Nested Resources