データを削除するには通常 DELETE メソッドを利用します.まず,削除のためのルートを定義します.
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');
Route::delete('/comments/{comment_id}', [CommentController::class, 'destroy']) -> name('comments.destroy');
続いてコントローラに destroy
関数を作成します.
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);
}
public function destroy(Request $request, $comment_id)
{
$comment = Comment::findOrFail($comment_id);
$comment->delete();
return response()->json();
}
}
削除機能の作成ができたはずなので,curl
コマンドで先ほど登録・更新した ID=4 のコメントを削除します.その後,一覧で取得すると削除できていることがわかります.
C:\Users\Rinsaka>curl -X DELETE http://192.168.56.101:8000/api/comments/4 ⏎ [] 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"}]} C:\Users\Rinsaka>