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?

【LaravelAPI】ファイル構成とざっくりとしたルール (MVC + S)

Last updated at Posted at 2025-04-17

はじめに

3年ほどLaravelでAPIを開発してきました。
試行錯誤していった結果、この書き方だと保守も容易かつ実装もスムーズに行えました。

普段はMVC+Sで開発していて、Repositoryは採用していないので、その点はご注意ください。
またもっといい方法だったり、案があるかたはご提案いただけますと幸いです。

api.php

Route::groupは文字列検索で引っ掛け辛いので、使用しない。
実装者ではない人が保守対応するとき、フロント→APIと探して文字列検索出来ないとかなりストレスになります!(管理者画面がある場合は後半のパスが被りやすいのでなおさら)

良くない例

Route::group(['prefix' => '/users'], function () {
  Route::post('/', 'Users\IndexController');
  Route::post('/{id}', 'Users\GetController');
});

いい例

Route::post('/users', 'Users\IndexController');
Route::post('/users/{id}', 'Users\GetController');

Controller

Controllerのディレクトリは以下の構造とします。
可能な限りControllerの名前はAPIのURIと紐づけやすい名前にしましょう!
ControllerからDBの操作は行いません。

Controllers/
 ├ Users/
     ├ IndexController.php // 一覧
     ├ GetController.php  // 1件取得
     ├ EditController.php  // 編集
     ├ RegisterController.php  // 登録
     ├ DeleteController.php  // 削除

Request

Requestの構造は基本的にControllerと同じです。

バリデーションの和名にvalidation.phpは使用していません。
変数名が被った時に結局各Requstで上書きが必要になり、保守でバグを生みかねないためです。

Requests/
 ├ Users/
     ├ UserRequest.php  // ここにパラメータの和名と共通バリデーションを書きます
     ├ IndexRequest.php  // UserRequestを継承
     ├ EditRequest.php  // UserRequestを継承
     ├ RegisterRequest.php  // UserRequestを継承

Service

複雑な処理や、DB操作などはServiceで行います。 こちらもAPIのURIに沿って作成しましょう。

Services/
 ├ UserService.php
 ├ ProjectService.php

Resource

Resourceは基本API設計のModelごとに作成します。

Resources/
 ├ UserResource.php
 ├ BackupResource.php

Resourceへ各モデルに書いてあるリレーション先の情報も書きます。
whenLoaded()を使用することによって、with loadされた値場合のみ値が返却されます。

サンプル
UserResource.php

    public function toArray($request)
    {
        return [
            'id' => $this->id,
            "name" => $this->name,
            "email" => $this->email,
            'relations' => RelationResource::collection($this->whenLoaded('tRelations')),
        ];
    }

ResourceCollectionの使い所

ResourceをカスタマイズできるCollectionという機能があります。
こちらは既存レスポンスに +α したいときなどに利用しましょう!

Test

各テストのメソッド名は test_ステータスコード_テスト の内容とする

public function test_200_ユーザ取得() {}
public function test_404_存在しないユーザを指定() {}
public function test_422_required() {} // 必須項目のテスト
public function test_422_max() {}  // 最大文字数のテスト

ディレクトリ構成は以下のようになります。Resourceのテストを書き、各エンドポイントのテストはidのみとします。
※リレーション先がある場合はリレーション先のIDが正しいかテストをしてください。

Feature/
  ├ Resources/
     ├ UserResourceTest.php
     ├ BackupResourceTest.php
 ├ Users/
     ├ IndexTest.php
     ├ GetTest.php
     ├ EditTest.php
     ├ RegisterTest.php

ステータスコード

200

  • 成功

201

  • 登録成功(idを返す)

401

  • 未ログイン
  • 不正なトークン

403

  • 権限エラー

404

  • 指定されたURIが存在しない場合
  • パスパラメータに紐づくデータが存在しなかった場合
    (例) GET /user/{id}
MUser::find($id)  undefiend

422

  • バリデーションエラー

500

  • 予期していないエラー
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?