Laravel provides intuitive methods for working with HTTP verbs in incoming requests, making it easy to handle different types of operations in your applications. The method() and isMethod() methods offer a clean way to identify and verify request types.
This functionality becomes particularly valuable when building RESTful APIs or handling complex form submissions where different HTTP methods trigger different business logic. It's especially useful for creating versatile controllers that can adapt their behavior based on the incoming request type.
// Basic method checking$method = $request->method(); // Returns 'GET', 'POST', etc.if ($request->isMethod('post')) { // Handle POST request}
Here's an example of a flexible resource handler:
<?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->handleGet($id), 'POST' => $this->handleCreate($request), 'PUT' => $this->handleUpdate($request, $id), 'DELETE' => $this->handleDelete($id), default => response()->json(['error' => 'Method not allowed'], 405) }; } private function handleGet($id = null) { if ($id) { return Resource::with('metadata') ->findOrFail($id); } return Resource::with('metadata') ->latest() ->paginate(20); } private function handleCreate(Request $request) { $resource = Resource::create($request->validated()); return response()->json([ 'message' => 'Resource created successfully', 'resource' => $resource->load('metadata') ], 201); } private function handleUpdate(Request $request, $id) { $resource = Resource::findOrFail($id); $resource->update($request->validated()); return response()->json([ 'message' => 'Resource updated successfully', 'resource' => $resource->fresh()->load('metadata') ]); } private function handleDelete($id) { Resource::findOrFail($id)->delete(); return response()->json(null, 204); }}
Example interactions:
// 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": "Method not allowed"}
The method() and isMethod() methods provide a clean way to implement method-specific logic while maintaining code organization.
