Laravel simplifies HTTP verb handling in incoming requests, streamlining diverse operation management within your applications. The method()
and isMethod()
methods efficiently identify and validate request types.
This feature is crucial for building RESTful APIs or managing complex form submissions where varying HTTP methods trigger distinct business logic. It's particularly beneficial for creating adaptable controllers that react dynamically to incoming request types.
// Basic method verification $method = $request->method(); // Returns 'GET', 'POST', etc. if ($request->isMethod('post')) { // Process POST request }
Here's a versatile resource handler example:
<?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); } }
Illustrative interactions:
<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>
The method()
and isMethod()
methods offer a structured approach to implementing method-specific logic while maintaining clean code organization.
The above is the detailed content of HTTP Method Verification in Laravel. For more information, please follow other related articles on the PHP Chinese website!