[Laravel] Using Resources in API Responses

Laravel Laravel

This article is an article of explanation about Resources in Laravel.

What is Resources?

When using the API to convert an Eloquent model into a JSON-format response, it is often necessary to change the key names, change fields that you do not want to output such as created_at, type conversions such as date/time format and flag values, and add fields for calculated values before outputting the response.

Resources makes these processes easy and common logic.

Creating Resource

Create it with the artisan command.

php artisan make:resource UserResource
Bash

The file is created under app/Http/Resources.

Resource Settings

The resulting app/Http/Resouces/UserResource.php has a toArray method, which is the JSON return value.

In this example, the response is to obtain user information, so returning the User’s Eloquent as it is would be inconvenient because the email address and password would be mixed in.

Therefore, the specified field and the first and last name are returned as one field.

app/Http/Resouces/UserResource.php
<?php

namespace App\Http\Resources;

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

class UserResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        // return parent::toArray($request);
        return [
            'id' => $request->id,
            'name' => $request->last_name . ' ' . $request->first_name,
            'birthday' => date('Y-m-d', strtotime($request->birthday)),
        ];
    }
}
PHP

Use Resource

Let’s use the UserResource you created and return it from the Controller.

If user information is passed as an argument when instantiating UserResource, the toArray method is called at output time and the information is output as JSON format.

PHP
<?php
 
namespace App\Http\Controllers;
 
use App\Services\UserService;
use App\Http\Resources\UserResource;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
 
class UserController extends Controller
{
    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }
 
    /**
     * get me
     */
    public function getMe(Request $request)
    {
        if (Auth::check()) {
            $user = Auth::user();
            return new UserResource($user); // Userモデルのインスタンスを引数に渡す
        }
 
        return response()->json([], Response::HTTP_UNAUTHORIZED);
    }
}
PHP

An example of the above response is shown below.

{
    "id": 12345,
    "name": "Mike Davis",
    "birthday": "1988-06-13"
}
JSON

summary

By using Resource, the user information was only acquired in this example, but it can be very useful to include similar content in the response to user registration or modification.

Also, when creating a social networking service, creating a UserResource for your own viewing and a UserResource for others’ viewing separately can prevent fields that should not be visible from being displayed, and prevent different response contents depending on the API.

It is often useful to create APIs, so you may want to consider using Resource, which is also more maintainable.

著者

30 years of experience as a web engineer, currently working as a freelance backend engineer.

PHP: ~30 years (Laravel 7 years / FuelPHP 5 years / CakePHP / custom frameworks)
JavaScript: ~20 years (React & Vue, 4 years each)
Cloud & Infrastructure: AWS (EC2, CloudFront, RDS, API Gateway, etc.) / GCP (BigQuery)

I have been writing PHP since version 4, back when the framework ecosystem was fragmented
and every team had their own approach. I've lived through the evolution firsthand —
from raw PHP and homegrown frameworks to the modern Laravel era —
which means I don't just know how to use a tool, but why it exists and what problem it replaced.

I work across system design, implementation, and operations, primarily on backend systems
for both product companies and contract-based projects.

On this blog, I write about the things I actually got stuck on, looked up, or figured out
in real-world projects. If something here unblocks even one person's day, that's enough for me.

千原 耕司をフォローする

役にたったと思ったら応援をお願いします m(._.)m

LaravelPHP
スポンサーリンク
シェアする
千原 耕司をフォローする
Copied title and URL