HTTP Method Verification in Laravel

Last updated on by

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

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
SerpApi

The Web Search API for Your LLM and AI Applications

Visit SerpApi
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Laravel Cloud logo

Laravel Cloud

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

Laravel Cloud
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $9500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises

The latest

View all →
Build a Laravel Scout Search Endpoint With the HTTP QUERY Method image

Build a Laravel Scout Search Endpoint With the HTTP QUERY Method

Read article
Enforce Per-Action Waiting Periods in Laravel with Cooldown image

Enforce Per-Action Waiting Periods in Laravel with Cooldown

Read article
First-Party Image Processing in Laravel 13.20 image

First-Party Image Processing in Laravel 13.20

Read article
Laravel Legacy Bridge: Carry Authenticated Sessions from a Legacy App into Laravel image

Laravel Legacy Bridge: Carry Authenticated Sessions from a Legacy App into Laravel

Read article
Laravel Quota: Usage Budgets for Calendar Periods image

Laravel Quota: Usage Budgets for Calendar Periods

Read article
Find the Security Vulnerabilities in Your Laravel App with Sensagraph image

Find the Security Vulnerabilities in Your Laravel App with Sensagraph

Read article