[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.

Follow me!

コメント

PAGE TOP
Copied title and URL