Cookie Consent by Free Privacy Policy Generator 📌 Getting data from resource responses before sending it to the client


✅ Getting data from resource responses before sending it to the client


💡 Newskategorie: Programmierung
🔗 Quelle: dev.to

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

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": ""
    }
}

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


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

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

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

Happy Tinkering ✌️

...

✅ Getting data from resource responses before sending it to the client


📈 63.33 Punkte

✅ How to Install Winscp FTP Client/SFTP Client/SCP Client (WinSCP Client) In Ubuntu


📈 26.24 Punkte

✅ Getting Started with Smart Home Notifications and Follow-up Responses


📈 24.11 Punkte

✅ Skype Insiders can now preview photos and files before sending them


📈 21.86 Punkte

✅ CVE-2023-39203 | Zoom Rooms Client/VDI Client resource consumption


📈 20.87 Punkte

✅ AI is Sending People To Jail -- and Getting it Wrong


📈 20.66 Punkte

✅ AI is Sending People To Jail -- and Getting it Wrong


📈 20.66 Punkte

✅ RansomFree Tool Detects Never-Seen-Before Ransomware Before It Encrypts Your Data


📈 20.6 Punkte

✅ RansomFree Tool Detects Never-Seen-Before Ransomware Before It Encrypts Your Data


📈 20.6 Punkte

✅ CVE-2024-24691 | Zoom Desktop Client/VDI Client/Meeting SDK/Rooms Client Zoom Meeting input validation


📈 19.68 Punkte

✅ CVE-2024-24697 | Zoom Desktop Client/VDI Client/Meeting SDK/Rooms Client untrusted search path


📈 19.68 Punkte

✅ From Dumb Data to Smart Responses: How RAG is Supercharging AI


📈 19.58 Punkte

✅ Mock The API Data (Request and Responses) With Playwright


📈 19.58 Punkte

✅ Lambda Unleashed: Mastering Massive Data Responses


📈 19.58 Punkte

✅ V8 JavaScript engine — Understanding JavaScript API Requests and Responses in the Data Fetching lifecycle


📈 19.58 Punkte

✅ Bing might soon have the capability to use images, videos, other data types in responses


📈 19.58 Punkte

✅ Best and worst data breach responses highlight the do's and don'ts of IR


📈 19.58 Punkte

✅ Fitbit Releases Major Software Update with SpO2 Data, Google Assistant Responses


📈 19.58 Punkte

✅ 6 data categories to learn for faster cybersecurity responses


📈 19.58 Punkte

✅ Cybersecurity regarding confidential data - Looking for responses to a survey!


📈 19.58 Punkte

✅ Encryption Before Compression or Compression Before Encryption?


📈 17.55 Punkte

✅ How good is Google Search’s AI Overview? Here are some of the most ridiculous responses


📈 16.53 Punkte

✅ Stream LLM Responses from Cache


📈 16.53 Punkte

✅ China Censors Social Media Responses To Proposal To Abolish Presidential Terms


📈 16.53 Punkte

✅ Privacy & confidentiality in COVID-19 responses | BDL121


📈 16.53 Punkte

✅ A faster, better way to prevent an AI chatbot from giving toxic responses


📈 16.53 Punkte

✅ Apple Watch owners receive Tim Cook responses to 'thank you' emails


📈 16.53 Punkte

✅ Lessons learned from six Lapsus$ incident responses Gabriela Nicolao & Santiago Abastante Deloitte


📈 16.53 Punkte

✅ The thought process and best practices for handling responses across each layer


📈 16.53 Punkte











matomo

Datei nicht gefunden!