How To Do Resource Data Wrapping In Laravel With Example

admin_img Posted By Bajarangi soft , Posted On 10-09-2020

When building an API, you may need a transformation layer that sits between your Eloquent models and the JSON responses that are actually returned to your application's users. Laravel's resource classes allow you to expressively and easily transform your models and model collections into JSON.

How To Do Resource Data Wrapping In Laravel With Example

Data Wrapping

By default, your outermost resource is wrapped in a data key when the resource response is converted to JSON.

So, for example:

To Create Resources visit our Bajarangisoft site.


1.Open app\Http\Resources\User.php and implement code as below

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class User extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */

    public static $wrap = 'user';

    public function toArray($request)
    {
        return ['data' => $this->collection];
    }
}


2.Create route in web.php

Route::get('/Users ', 'demoController@Users')->name('Users');
 

3.Create demoController and implement code to get all data from user model

php artisan make:controller demoController -mcr


4.Open demoController.php in app\Http\Controller folder and implement code as below

<?php
namespace App\Http\Controllers;

use App\Http\Resources\User as UserResource;
use App\User;

class demoController extends AppBaseController
{
    public function Users()
    {
        return new UserCollection(User::paginate());
    }
}


If you would like to disable the wrapping of the outermost resource, you may use the withoutWrapping method on the base resource class. Typically, you should call this method from your AppServiceProvider or another service provider that is loaded on every request to your application:

5.Open  app\providers\AppServiceProvider.php implement code as below

<?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();
    }
}


Wrapping Nested Resources
 

You have total freedom to determine how your resource's relationships are wrapped. 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.

You may be wondering if this will cause your outermost resource to be wrapped in two data keys. Don't worry, Laravel will never let your resources be accidentally double-wrapped, so you don't have to be concerned about the nesting level of the resource collection you are transforming:
 

<?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];
    }
}


Data Wrapping And Pagination

When returning paginated collections in a resource response, Laravel will wrap your resource data in a data key even if the withoutWrapping method has been called. This is because paginated responses always contain meta and links keys with information about the paginator's state:

for above example resource collection response looks like the following:

{
    "data": [
        {
            "id": 1,
            "name": "Eladio Schroeder Sr.",
            "email": "therese28@example.com",
        },
        {
            "id": 2,
            "name": "Liliana Mayert",
            "email": "evandervort@example.com",
        }
    ],
    "links":{
    "first": "http://example.com/pagination?page=1",
        "last": "http://example.com/pagination?page=1",
        "prev": null,
        "next": null
    },
    "meta":{
    "current_page": 1,
        "from": 1,
        "last_page": 1,
        "path": "http://example.com/pagination",
        "per_page": 15,
        "to": 10,
        "total": 10
    }
}

 

Related Post