データを更新するときには通常 PUT メソッドを利用します.まず,更新のためのルートを作成します.
routes/api.php (抜粋)
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::post('/comments', [CommentController::class, 'store']) -> name('comments.store');
Route::put('/comments/{comment_id}', [CommentController::class, 'update']) -> name('comments.update');
続いてコントローラに update
関数を作成します.
app/Http/Controllers/CommentController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Comment;
use App\Http\Resources\CommentResource;
class CommentController extends Controller
{
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);
}
}
更新機能の作成ができたはずなので,curl
コマンドで先ほど新規登録した ID=4 のコメントを更新します.このとき,タイトル (title) と本文 (body) を指定していますが,更新日時 (updated_at) も合わせて更新されていることを確認してください.
C:\Users\Rinsaka>curl -X PUT -d "title=update" -d "body=body update" http://192.168.56.101:8000/api/comments/4/ ⏎ {"comment":{"id":4,"title":"update","body":"body update","updated_at":"2023-12-16T15:10:04.000000Z"}} C:\Users\Rinsaka> C:\Users\Rinsaka>curl http://192.168.56.101:8000/api/comments/ ⏎ {"comments":[{"id":1,"title":"最初のコメント","body":"最初のコメントです!","updated_at":"2023-10-02T10:10:10.000000Z"},{"id":2,"title":"2つ目","body":"2つ目のコメントです!","updated_at":"2023-10-02T10:20:10.000000Z"},{"id":3,"title":"<三個目>のコメント","body":"シーダによってテストデータを設定します.","updated_at":"2023-10-02T10:30:10.000000Z"},{"id":4,"title":"update","body":"body update","updated_at":"2023-12-16T15:10:04.000000Z"}]} C:\Users\Rinsaka>