Laravel Tutorials

HTTP Method Verification in Laravel

Published
HTTP Method Verification in Laravel image

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.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
Slow Job Alerts and Replica Commit IDs in Laravel 13.40 image

Slow Job Alerts and Replica Commit IDs in Laravel 13.40

Read article
Flock: A Free, Native Herd Alternative for Laravel image

Flock: A Free, Native Herd Alternative for Laravel

Read article
Live Props for Real-Time Updates in Inertia.js v3.11 image

Live Props for Real-Time Updates in Inertia.js v3.11

Read article
Cooldown Dependency Policy now in Composer 2.11 image

Cooldown Dependency Policy now in Composer 2.11

Read article
Email Sending and Testing for Laravel in One Account image

Email Sending and Testing for Laravel in One Account

Read article
Decide with Jev: Tie Every AI Check to the Exact Draft image

Decide with Jev: Tie Every AI Check to the Exact Draft

Read article