Laravel Tutorials

Streamlining Context Validation in Laravel

Published
Streamlining Context Validation in Laravel image

Laravel enhances context validation with the introduction of missing() and missingHidden() methods, offering clean boolean checks to verify key existence in your Context service.

When developing with Laravel's Context service, you frequently need to determine whether specific keys exist before attempting to use them. These new methods provide a direct way to confirm context availability without resorting to negated exists checks.

Here's how these methods work in practice:

// Populate context with values
Context::add('referer', $request->header('referer'));
Context::addHidden('session', $request->session()->getId());
 
// Verify regular keys existence
Context::missing('referer'); // false
Context::missing('user_agent'); // true
 
// Check hidden keys existence
Context::missingHidden('referer'); // true (not a hidden key)
Context::missingHidden('session'); // false

These additions offer a more intuitive and readable alternative to the traditional approach of negating has() method checks. By explicitly asking if something is missing rather than negating an existence check, your code becomes more semantically clear, especially when making conditional logic decisions based on context availability.

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 →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article