Avoid Multiple Condition Checks in Laravel Using whenFilled()

Run logic only when request input is present — clean and readable.

  • 03 Apr, 2026
  • 20 Views

Avoid Multiple Condition Checks in Laravel Using whenFilled()

The Problem: Repeated Input Checks

In Laravel applications, handling request input often looks like this:

if ($request->has('search') && $request->search !== '') {
    // apply filter
}

As filters grow, this becomes messy.

The Cleaner Solution: whenFilled()

Laravel provides whenFilled() to simplify this.

$request->whenFilled('search', function ($value) {
    // apply filter
});

Real Project Example

Imagine filtering users by email:

$query = User::query();
$request->whenFilled('email', function ($email) use ($query) {
    $query->where('email', $email);
});
$users = $query->get();

No need for manual checks.

Why This Is Useful

It helps you:

  • Remove repetitive conditions
  • Keep controllers clean
  • Improve readability
  • Handle optional inputs easily

When to Use It

Use it when:

  • Working with request filters
  • Building APIs
  • Handling optional form inputs 


Share: