DEV Community

Cover image for Getting data from resource responses before sending it to the client
Phyo Thiha
Phyo Thiha

Posted on

Getting data from resource responses before sending it to the client

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
  2. Including extra meta data with a resource response

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

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

public function index()
{
    return new UserCollection(User::paginate());
}
Enter fullscreen mode Exit fullscreen mode

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.

{
    "success": true,
    "statusCode": 200,
    "data": [
        {}, 
        {}
    ],
    "pagination": {
        "current_page": "",
        "last_page": "",
        "per_page": "",
        "total": ""
    }
}
Enter fullscreen mode Exit fullscreen mode

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.

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


Enter fullscreen mode Exit fullscreen mode

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

<?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);
    }
}
Enter fullscreen mode Exit fullscreen mode

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

dd($collection->response());
Enter fullscreen mode Exit fullscreen mode

JsonReponse

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

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

Happy Tinkering ✌️

Top comments (0)