0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

マスタデータ取得API

Posted at

仕事で複数のマスタテーブルをAPI取得することがあり苦戦したため備忘録として

新米エンジニアです
間違えていたり他にいいやり方があれば優しく教えてください

前提

すでにmigrationでテーブルを作成したのちseederでデーターを作成されている状態

全体の流れ

routes/api.php→controller→Service→resource→Model

1.Resource

resourceとは
モデルやモデルコレクションを簡単にJSONデータへと変換してくれる

artisanコマンドでresourceファイルを作成する

$ php artisan make:resource TestResource

App\Http\Resources\TestResourceが生成される
toArrayの中身を書き換える
※今回は複数のテーブルをAPI取得しましたが2パターンに分かれていたため2つ作成しています

<?php

namespace App\Http\Resources;

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

class TwoResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name
        ];
    }
}
<?php

namespace App\Http\Resources;

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

class ThreeResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email
        ];
    }
}

2.Service

serviceでResourceを使用してデータを取得する

::collection
・Laravelのelquentリソースクラス内で定義されたメソッド
・モデルのコレクションをリソースのコレクションに変換するときにつかう

<?php

namespace App\Services;
use App\Http\Resources\TwoResource;
use App\Http\Resources\ThreeResource;
use App\Models\A;
use App\Models\B;
use App\Models\C;
use App\Models\D;


class TestService
{
    public function createData()
    {

        return [
            'a_table' => TwoResource::collection(A::all()),
            'b_table' => ThreeResource::collection(B::all()),
            'c_table' => TwoResource::collection(C::all()),
            'd_table' => TwoResource::collection(D::all()),
            ];
    }

3.Controller

__constructとは
クラスからインスタンスを生成する際(new を行う際)に最初に実行される関数

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Services\TestService;



class TestController extends Controller
{

    private $testService;

    public function __construct(TestService $testService)
    {
        $this->testService = $testService;
    }

    public function getMasterData()
    {
        $jsonData = $this->testService->createData();
       
        return $this->createResponse($jsonData);
    }
   
    private function createResponse(mixed $data): array
    {    
        return ['data' => $data,
                'error' => [
                    'message' => '',
                ]
               ];
    }
   
}

postmanで確認したところJSON形式で取得できました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?