Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

skoobi's avatar
Level 13

Wrapping API Resource with something other than data

Hi all...

I've been trying to wrap my API Resource in a wrapper named modules rather than data but it wont change the output when I add private static $wrap = 'modules';

The other output I needed to get right was to remove the outer shell as it were for the users api resource so it doesn't have the data in it at all...

So, here's my Modules API Resource.

// Route

Route::middleware('auth:api')->get('/modules', function () {
    return ModulesResource::collection(Module::active()->get());
});


//ModulesResource.php 

class ModulesResource extends JsonResource
{
    /**
     * The "data" wrapper that should be applied.
     *
     * @var string
     */
    public static $wrap = 'modules';

    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'module_title' => $this->title,
            'playlist_steps' => ModuleStepsResource::collection($this->module_steps)
        ];
    }
}

but the output is still

// What it outputs
{
    "data": [
        	{}
	]
}

// What I want it to output
{
    "modules": [
        	{}
	]
}

and for my users resource I want to get rid of the above "data" part completely if thats possible.

Any help would be grateful.

Cheers

0 likes
2 replies
frankielee's avatar
Level 29

You have to use Resource Collection to do that.

This public static $wrap = 'modules'; only works when

 return new ModulesResource(Module::active()->first());

To do: ModuleCollection

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\ResourceCollection;
use App\Http\Resources\ModulesResource; // replace the name with your resource
class ModuleCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */

public static $wrap = "modules";
    public function toArray($request)
    {
        return   ModulesResource::collection($this->collection);
    }
}

https://laravel.com/docs/7.x/eloquent-resources#resource-collections

3 likes
skoobi's avatar
Level 13

Thanks for that, Ive just started using API Resources and now starting to see how they're used and work.

Cheers.

Please or to participate in this conversation.