Laravel 10 入門トップページ


目次

  1. API とプロジェクトの概要
  2. プロジェクトの作成と初期設定
  3. データベースのマイグレーション
  4. シーダによるコメントデータの登録
  5. モデルの生成
  6. リソースの生成
  7. GETメソッドを利用した個別コメント取得のAPI作成
  8. 日本語文字列の表示と日時の調整
  9. GETメソッドを利用したコメント一覧取得のAPI作成
  10. データのラップ
  11. POSTメソッドを利用したコメントの新規投稿APIの作成
  12. PUTメソッドを利用したコメント更新APIの作成
  13. DELETEメソッドを利用したコメント削除APIの作成
  14. シーダの拡張
  15. ページネーションの実装
  16. 個別コメントをコントローラで取得
  17. Postman の利用
  18. ユーザ情報を登録する
  19. Sanctum によるユーザ認証
  20. ログインとトークン
  21. コメントとユーザのリレーションシップ
  22. 新規投稿時にユーザIDを記録する
  23. コメントからユーザ名を表示するリレーションシップ
  24. ユーザからコメント一覧を取得するリレーションシップ
  25. 更新と削除の権限設定
  26. 発行済みトークンの取得
  27. トークンの有効期限
  28. レート制限
  29. 閲覧権限の緩和

Laravel で API を開発する

個別コメントをコントローラで取得

これまで個別コメントは次のようにルートの定義の中で取得していました.

routes/api.php (抜粋)Route::get('/comments/{id}', function (string $id) {
    return new CommentResource(Comment::findOrFail($id));
});

もちろんこのままでも良いのですが,コメントに関するその他の機能はコントローラでまとめて取得や操作をしているので,個別コメントの取得に関する機能もコントローラに移行します.

まず,ルートの定義を次のように変更します.具体的には,コントローラを呼び出す定義(34行目)を追加し,不要になった箇所をコメントアウトするか削除します.

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
// use App\Http\Resources\CommentResource;
// use App\Http\Resources\CommentCollection;
// use App\Models\Comment;
use App\Http\Controllers\CommentController;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "api" middleware group. Make something great!
|
*/

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

// Route::get('/comments/{id}', function (string $id) {
//     return new CommentResource(Comment::findOrFail($id));
// });

// Route::get('/comments', function () {
//     return new CommentCollection(Comment::get());
// });

Route::get('/comments', [CommentController::class, 'index']) -> name('comments.index');
Route::get('/comments/{comment_id}', [CommentController::class, 'show']) -> name('comments.show');
Route::post('/comments', [CommentController::class, 'store']) -> name('comments.store');
Route::put('/comments/{comment_id}', [CommentController::class, 'update']) -> name('comments.update');
Route::delete('/comments/{comment_id}', [CommentController::class, 'destroy']) -> name('comments.destroy');

次にコントローラに show 関数を作成します.これによりコメントの取得や操作に関する機能がコントローラに集約されました.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Comment;
use App\Http\Resources\CommentResource;
use App\Http\Resources\CommentCollection;

class CommentController extends Controller
{
    public function index()
    {
        $comments = Comment::orderBy('updated_at','DESC')
                    ->paginate(3);
        return new CommentCollection($comments);
    }

    public function show($comment_id)
    {
        $comment = Comment::findOrFail($comment_id);
        return new CommentResource($comment);
    }

    public function store(Request $request)
    {
        $comment = new Comment();
        $comment->title = $request->title;
        $comment->body = $request->body;
        $comment->save();
        return new CommentResource($comment);
    }

    public function update(Request $request, $comment_id)
    {
        $comment = Comment::findOrFail($comment_id);
        $comment->title = $request->title;
        $comment->body = $request->body;
        $comment->save();
        return new CommentResource($comment);
    }

    public function destroy(Request $request, $comment_id)
    {
        $comment = Comment::findOrFail($comment_id);
        $comment->delete();
        return response()->json();
        // return new CommentResource($comment);
    }
}

これまで通り個別のコメントを curl コマンドで取得できることを確認しておきます.

C:\Users\Rinsaka>curl http://192.168.56.101:8000/api/comments/1/ ⏎
{"comment":{"id":1,"title":"最初のコメント","body":"最初のコメントです!","updated_at":"2023-10-02T10:10:10.000000Z"}}
C:\Users\Rinsaka>curl http://192.168.56.101:8000/api/comments/100/ ⏎
{"comment":{"id":100,"title":"三宅 結衣","body":"4508690  東京都高橋市西区加納町山口5-5-7 \/ shuhei92@example.org","updated_at":"2023-11-07T22:56:49.000000Z"}}
C:\Users\Rinsaka>

目次に戻る