LaravelのHTTPメソッド検証

Johnathan Smith
Johnathan Smithオリジナル
2025-03-05 16:14:231018ブラウズ

HTTP Method Verification in Laravel

Laravelは、入ってくるリクエストでHTTP動詞処理を簡素化し、アプリケーション内の多様な運用管理を合理化します。 method()およびisMethod()メソッドは、リクエストタイプを効率的に識別および検証します。 この機能は、RESTFUL APIを構築したり、異なるHTTPメソッドが異なるビジネスロジックをトリガーする複雑なフォーム送信を管理するために重要です。 着信リクエストタイプに動的に反応する適応可能なコントローラーを作成するのに特に有益です。

これが多用途のリソースハンドラーの例です。

// Basic method verification
$method = $request->method();  // Returns 'GET', 'POST', etc.
if ($request->isMethod('post')) {
    // Process POST request
}

実例相互作用:

<?php

namespace App\Http\Controllers;

use App\Models\Resource;
use Illuminate\Http\Request;

class ResourceController extends Controller
{
    public function handle(Request $request, $id = null)
    {
        return match ($request->method()) {
            'GET' => $this->getHandler($id),
            'POST' => $this->createHandler($request),
            'PUT' => $this->updateHandler($request, $id),
            'DELETE' => $this->deleteHandler($id),
            default => response()->json(['error' => 'Unsupported method'], 405)
        };
    }

    private function getHandler($id = null)
    {
        if ($id) {
            return Resource::with('metadata')->findOrFail($id);
        }
        return Resource::with('metadata')->latest()->paginate(20);
    }

    private function createHandler(Request $request)
    {
        $resource = Resource::create($request->validated());
        return response()->json(['message' => 'Resource created', 'resource' => $resource->load('metadata')], 201);
    }

    private function updateHandler(Request $request, $id)
    {
        $resource = Resource::findOrFail($id);
        $resource->update($request->validated());
        return response()->json(['message' => 'Resource updated', 'resource' => $resource->fresh()->load('metadata')]);
    }

    private function deleteHandler($id)
    {
        Resource::findOrFail($id)->delete();
        return response()->json(null, 204);
    }
}

および
<code>// GET /api/resources/1
{
    "id": 1,
    "name": "Example Resource",
    "status": "active",
    "metadata": {
        "created_by": "john@example.com",
        "last_accessed": "2024-02-01T10:30:00Z"
    }
}

// PUT /api/resources/1 with invalid method
{
    "error": "Unsupported method"
}</code>
メソッドは、クリーンコード組織を維持しながら、メソッド固有のロジックを実装するための構造化されたアプローチを提供します。

以上がLaravelのHTTPメソッド検証の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。