Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[9.x] Fixes the issue of overriding $wrap property #43463

Closed
wants to merge 1 commit into from
Closed

[9.x] Fixes the issue of overriding $wrap property #43463

wants to merge 1 commit into from

Conversation

mahmoudmohamedramadan
Copy link
Contributor

So, let me explain the issue in more detail:

Laravel says that I can change data keyword via defining a $wrap attribute on the resource class like so,

/**
 * The "data" wrapper that should be applied.
 *
 * @var string|null
 */
 public static $wrap = 'user';

But when I tried this way nothing changed as we can see in the next figure:

before-this-PR


If this PR gets merged

As we can see in the next figure that this issue has been solved 🎉

after-PR-was-accepted

@rodrigopedra
Copy link
Contributor

This is a major breaking change. $wrap works fine for individual resources.

An application using $wrap for individual resources (the default behavior) is already expecting unwrapped resource collections when calling its ::collection(...) method.

I am not opposing to you to propose this change, but this should be sent to master instead.

In the meanwhile you can use the docs suggestions on how to wrap resource collections:

If you would like all resource collections to be wrapped in a data key, regardless of their nesting, you should define a resource collection class for each resource and return the collection within a data key.

<?php
 
namespace App\Http\Resources;
 
use Illuminate\Http\Resources\Json\ResourceCollection;
 
class CommentsCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return ['data' => $this->collection];
    }
}

reference: https://laravel.com/docs/9.x/eloquent-resources#wrapping-nested-resources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants