Logo

dev-resources.site

for different kinds of informations.

Including extra meta data with a resource response

Published at
4/22/2024
Categories
laravel
eloquent
apiresource
metadata
Author
phyothiha
Author
9 person written this
phyothiha
open
Including extra meta data with a resource response

In the previous article, I explained about customizing pagination structure.

Today, I want to show returing a JSON response from the controller method with extra top-level keys along with data and pagination keys using the resource class.

As you may know, there is also an organizational standard or preferred format for JSON API responses. I will stick with a pretty basic format.

Success Response Format

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

A very simple way to return a response from the controller method will be

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

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

💡Why use resource collection over resource?

If you would like to customize the resource collection response, you may create a dedicated resource to represent the collection

As you have read and followed the previous article, the return format will be

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

If not, the default structure will return

{
    "data": [],
    "links": {},
    "meta": {}
}
Enter fullscreen mode Exit fullscreen mode

So how can we achieve the response format described above?

Well, you might have guessed, but

public function index()
{
    return response()->json([
        'success' => true,
        'statusCode' => 200,
        // how should I use the resource collection class here?
    ], 200);
}
Enter fullscreen mode Exit fullscreen mode

Or you might be going the other way around. Create a new resource collection class and add success and statusCode keys.

Method #1 (Adding Meta Data)

<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\ResourceCollection;

class UserCollection extends ResourceCollection
{
    public function toArray(Request $request): array
    {
        return [
            'success' => true,
            'statusCode' => 200,
            'data' => $this->collection,
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

Method #2 (Top Level Meta Data)

<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\ResourceCollection;

class UserCollection extends ResourceCollection
{
    public function toArray(Request $request): array
    {
        return parent::toArray($request);
    }

    public function with(Request $request): array
    {
        return [
            'success' => true,
            'statusCode' => 200,
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

As you see, success and statusCode sit inside the resource collection class. You already know what kind of approach to use to reduce code duplication.

A cliffhanger: What if I want to create a trait and use it in the controller file?

Happy Tinkering ✌️

metadata Article's
30 articles in total
Favicon
How to customize Next.js metadata
Favicon
Metadata, Data Dictionary, and Catalog in a DBMS: Understanding the Differences and Their Roles
Favicon
Improving TypeScript Metadata Type Safety with ts-reflector
Favicon
Reflect MetaData
Favicon
The Machines Would Appreciate More Structured Data
Favicon
How to Assign Different Version Data to a Rented Strategy via Strategy Rental Code Metadata
Favicon
Including extra meta data with a resource response
Favicon
PicoGym Practice Write Up for Forensics Challenge(10pt): information
Favicon
Connecting with your Database with the Information Schema
Favicon
Next.js: How to Create Open Graph Social Media Cards
Favicon
Next.js: favicon, SVG icon, Apple & Chrome icons
Favicon
Security Tips: Metadata
Favicon
Error Message Bibliometrix R - replacement has 0 rows, data has XXX
Favicon
Securing Your Data Lake with Apache Atlas: The Ultimate Guide
Favicon
What I learned as a Subject Matter Expert while creating my product
Favicon
Why metadata management is indispensable for successful data evaluation
Favicon
First P2E game on Tableland (2)
Favicon
AppstoreSpy’s API – Your fresh and keen metadata
Favicon
What is .metadata file in Flutter Project?
Favicon
First P2E game on Tableland (1)
Favicon
Use Aiven's metadata parser to understand how your data flows
Favicon
Badges - TL;DR for your repository's README
Favicon
Elixir logging to (multiple) file(s) using metadata_filter
Favicon
Some housekeeping (why I help as a mod)
Favicon
ShardingSphere’s Metadata Loading Process
Favicon
Metadata: What Is It, And How Does It Boost Your Business?
Favicon
Resumo sobre a versão 2 do serviço de metadados de instância AWS EC2 (IMDSv2)
Favicon
Check your head 🤔
Favicon
How to gets uploaded image Metadata on the front-end
Favicon
On metadata in Hugo - or turning tags to keywords

Featured ones: