Getting data from resource responses before sending it to the client
Tags: laravel, eloquent, apiresource, response
Published: 2024-04-24 14:28:33

Before telling the cliffhanger from the previous article and want to know what is going on here, check out those articles first in order.

1. [Customizing API Resource Pagination Structure
](https://dev.to/phyothiha/customizing-api-resource-pagination-structure-3ckp)
2. [Including extra meta data with a resource response](https://dev.to/phyothiha/including-extra-meta-data-with-a-resource-response-2bf8)

As you have already read, resources can be returned from the controller method.

```php
use App\Http\Resources\UserCollection;
use App\Models\User;

public function index()
{
    return new UserCollection(User::paginate());
}
```

You want to respond with this format for the success response and achieve it by adding meta data to the resource collection class, knowing that every response contains `success` and `statusCode` keys.

```json
{
    "success": true,
    "statusCode": 200,
    "data": [
        {}, 
        {}
    ],
    "pagination": {
        "current_page": "",
        "last_page": "",
        "per_page": "",
        "total": ""
    }
}
```

Today, I am going to show you how to create a trait class and use it everywhere you want to be. 

You may use the trait class in the controller.

```php
use App\Http\Resources\UserCollection;
use App\Models\User;
use App\Traits\ResponseJson;

class UserController extends Controller
{
    use ResponseJson;

    public function index()
    {
        return $this->paginateResponse(
            new UserCollection(User::paginate())
        );
    }
}


```

I will create a file called `ResponseJson.php` under the App/Traits directory with two methods.

```php
<?php

namespace App\Traits;

use Illuminate\Http\Response;

trait ResponseJson
{
    protected $successJson = [
        'success' => true,
        'status_code' => 200,
        'message' => '',
        'data' => [],
    ];

    public function paginateResponse($collection)
    {
        // this is the trick
        $class = $collection->response()->getData();

        $this->successJson['data'] = $class->data;

        $this->successJson['pagination'] = $class->pagination;

        return response()->json($this->successJson, 200);
    }
}
```

As you see, `response()` method on the resource collection class return `Illuminate\Http\JsonResponse` class contains headers, content, data, and other attributes and methods.

```php
dd($collection->response());
```

![JsonReponse](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tg6ekyrnti8kqvrrb81h.png)

You need to call the getter method `getData()` on the result and access the class properties that are returned by stdClass.

Finally, there is no need to create and extend a base resource collection class to include the desired keys. Now you have a dedicated trait class and can add new methods if necessary.

For example

```php
<?php

namespace App\Traits;

use Illuminate\Http\Response;

trait ResponseJson
{
    protected $successJson = [
        'success' => true,
        'status_code' => 200,
        'message' => '',
        'data' => [],
    ];

    protected $errorJson = [
        'success' => false,
        'status_code' => 500,
        'message' => '',
        'errors' => [],
    ];

    public function successResponse($data = [], $message = '', $statusCode = Response::HTTP_OK)
    {
        $this->successJson['data'] = $data;

        $this->successJson['message'] = $message;

        return response()->json($this->successJson, $statusCode);
    }

    public function errorResponse($error = [], $message, $statusCode)
    {
        $this->errorJson['errors'] = $error;

        $this->errorJson['status_code'] = $statusCode;

        $this->errorJson['message'] = $message;

        return response()->json($this->errorJson, $statusCode);
    }

    public function paginateResponse($collection)
    {
        $class = $collection->response()->getData();

        $this->successJson['data'] = $class->data;

        $this->successJson['pagination'] = $class->pagination;

        return response()->json($this->successJson, 200);
    }
}
```

Happy Tinkering ✌️