Get expert guidance in a few days with a Laravel code review

Handling Request Data Presence in Laravel

Last updated on by

Handling Request Data Presence in Laravel image

Laravel's whenHas method provides an elegant way to execute code based on input presence in requests. This feature is particularly useful for handling optional fields and conditional updates, reducing the need for repetitive presence checks.

This approach shines particularly in form submissions where certain fields trigger specific business logic - for example, when a user opts into email notifications, you might need to validate and store additional email-related preferences.

// Simple presence check
 
$request->whenHas('name', function ($name) {
// Process name when present
});

Here's an example of a notification preferences manager:

// app/Controllers/PreferencesController.php
<?php
 
namespace App\Http\Controllers;
 
use App\Models\UserPreferences;
use Illuminate\Http\Request;
 
class PreferencesController extends Controller
{
 
public function update(Request $request, UserPreferences $preferences)
 
{
$request->whenHas('email_frequency',
function ($frequency) use ($preferences) {
$preferences->update([
'email_frequency' => $frequency,
'last_email_update' => now()
]);
}
);
 
$request->whenHas('push_enabled',
function ($enabled) use ($preferences) {
$preferences->update([
'push_enabled' => $enabled,
'push_updated_at' => now()
]);
},
function () use ($preferences) {
$preferences->update([
'push_enabled' => false,
'push_updated_at' => now()
]);
}
);
 
return response()->json([
'message' => 'Preferences updated successfully',
'preferences' => $preferences->fresh()
]);
}
}

Example usage:

// Input with some preferences
 
{
"email_frequency": "weekly"
}
 
// Response
 
{
"message": "Preferences updated successfully",
"preferences": {
"email_frequency": "weekly",
"last_email_update": "2024-02-01T10:30:00.000000Z",
"push_enabled": false,
"push_updated_at": "2024-02-01T10:30:00.000000Z"
}
}

The whenHas method simplifies conditional request processing while maintaining clean, readable code structure.

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
Laravel Cloud

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

Visit Laravel Cloud
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Laravel Cloud logo

Laravel Cloud

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

Laravel Cloud
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
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
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
Tinkerwell logo

Tinkerwell

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

Tinkerwell
SerpApi logo

SerpApi

Access real-time search engine results through a simple API—no more scraping headaches! Use it for AI applications, SEO tools, product research, travel information, and more

SerpApi
PhpStorm logo

PhpStorm

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

PhpStorm
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
Lucky Media logo

Lucky Media

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

Lucky Media

The latest

View all →
Laravel Brain: Visualize Your Application's Request Lifecycle image

Laravel Brain: Visualize Your Application's Request Lifecycle

Read article
Laravel Shopper: A Headless E-Commerce Admin Panel for Laravel image

Laravel Shopper: A Headless E-Commerce Admin Panel for Laravel

Read article
Chevere Workflow: A Declarative PHP Workflow Engine with Async Job Execution image

Chevere Workflow: A Declarative PHP Workflow Engine with Async Job Execution

Read article
Laravel Schema Sentinel: Detect and Fix Database Schema Drift image

Laravel Schema Sentinel: Detect and Fix Database Schema Drift

Read article
Laravel Web Push Notifications image

Laravel Web Push Notifications

Read article
RedBerry to Host Georgia's First Laravel Meetup in Tbilisi image

RedBerry to Host Georgia's First Laravel Meetup in Tbilisi

Read article