🎉🎉 Larasense is officially launched 🎉🎉
- Your Hub for Laravel News, Trends & Updates

Add Logic To Laravel Requests Conditionally

laravel
release
request
Nabil Hassen
Nabil Hassen
Dec 17, 2024
Laravel Request Object
Last updated on Dec 17, 2024
Table of contents:

Introduction

Laravel 11.35.0 introduces a powerful addition to the Request class — support for the when() method via the Conditionable trait. This feature, contributed by Ahmet İmrak, allows developers to apply conditional logic seamlessly when working with incoming request data. This makes your code cleaner, more expressive, and aligns the Request class with other conditionable parts of the Laravel ecosystem like the Query Builder.

The Problem

Previously, conditional handling of incoming request data often required verbose if statements or repetitive inline checks. For example:

if ($this->input('account_id')) {
$this->merge(['account_name' => Account::getName($this->input('account_id'))]);
} else {
$this->merge(['account_name' => null]);
}
 
if ($this->input('contact_id')) {
$this->merge(['contact_name' => Contact::getName($this->input('contact_id'))]);
} else {
$this->merge(['contact_name' => null]);
}

Such conditional logic, though functional, is repetitive and harder to maintain as the number of conditions grows.

The Solution: when() Method

With Laravel 11.35.0, the Request class now uses the Conditionable trait, enabling the use of the when() method to streamline conditional operations. Here’s an example of how the same logic looks with the new method:

protected function prepareForValidation(): void
{
$this->when($this->input('account_id'),
fn (Request $req, int $accountId) => $req->merge(['account_name' => Account::getName($accountId)]),
fn (Request $req) => $req->merge(['account_name' => null])
)->when($this->input('contact_id'),
fn (Request $req, int $contactId) => $req->merge(['contact_name' => Contact::getName($contactId)]),
fn (Request $req) => $req->merge(['contact_name' => null])
);
}

How It Works

The when() method applies a callback when the given condition resolves to a truthy value. Additionally, you can pass a "default" callback to handle cases where the condition is falsy.

Method Signature:

public function when($value = null, ?callable $callback = null, ?callable $default = null);
  • $value: The condition to evaluate (e.g., a request input value).
  • $callback: Executed if the condition is truthy.
  • $default: Executed if the condition is falsy.

Key Benefits

  1. Cleaner Code: Removes repetitive if statements and simplifies conditional logic.
  2. Readability: Code becomes more expressive and easier to follow.
  3. Reusability: Aligns the Request class with other conditionable components like Collections and Query Builder.

Real-World Example

Imagine you’re preparing request data for validation. With the when() method, you can handle multiple conditionals concisely:

Before:

if ($this->input('is_admin')) {
$this->merge(['role' => 'admin']);
} else {
$this->merge(['role' => 'user']);
}

After (Laravel 11.35.0):

$this->when($this->input('is_admin'),
fn (Request $req) => $req->merge(['role' => 'admin']),
fn (Request $req) => $req->merge(['role' => 'user'])
);

This results in cleaner and more maintainable code.

Conclusion

The addition of the when() method to the Request class in Laravel 11.35.0 is a significant improvement for developers. Thanks to Ahmet İmrak's contribution, conditional logic in request data handling is now more elegant, readable, and aligned with Laravel’s fluent and expressive syntax.

Upgrade to Laravel 11.35.0 to take advantage of this feature and simplify your request processing logic.

Nabil Hassen
Nabil Hassen
Full Stack Web Developer

Stay Updated.

I'll you email you as soon as new, fresh content is published.

Thanks for subscribing to my blog.

Latest Posts