In Laravel 11, the approach to changing the default JSON resource wrapper has been updated. You can still set the $wrap property, but the way you do it might have changed slightly. Here’s how you can achieve this in Laravel 11:
-
Setting the
$wrapProperty in the Resource Class:You can still set the
$wrapproperty in your resource class to change the default wrapper. Here’s an example:<?php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\JsonResource; class YourResource extends JsonResource { /** * The "data" wrapper that should be applied. * * @var string|null */ public static $wrap = 'test'; /** * Transform the resource into an array. * * @param \Illuminate\Http\Request $request * @return array */ public function toArray($request) { return [ 'id' => $this->id, 'name' => $this->name, // Add other fields here ]; } } -
Disabling the Wrapper Globally:
If you want to disable the wrapper globally for all resources, you can do so in the
AppServiceProvideror any other service provider by using thewithoutWrappingmethod:<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Illuminate\Http\Resources\Json\JsonResource; class AppServiceProvider extends ServiceProvider { /** * Register any application services. * * @return void */ public function register() { // } /** * Bootstrap any application services. * * @return void */ public function boot() { JsonResource::withoutWrapping(); } } -
Customizing the Wrapper Dynamically:
If you need to customize the wrapper dynamically, you can override the
withmethod in your resource class:<?php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\JsonResource; class YourResource extends JsonResource { /** * Transform the resource into an array. * * @param \Illuminate\Http\Request $request * @return array */ public function toArray($request) { return [ 'id' => $this->id, 'name' => $this->name, // Add other fields here ]; } /** * Customize the additional data that should be included with the resource array. * * @param \Illuminate\Http\Request $request * @return array */ public function with($request) { return [ 'meta' => [ 'custom' => 'value', ], ]; } }
By following these steps, you should be able to change the default JSON resource wrapper in Laravel 11. If the static $wrap property is not working as expected, ensure that you are using the correct namespace and that there are no typos in your code.