exists() vs has() in Laravel: Best Practices for Query Parameters

Are you working with query parameters in Laravel? 🤔 There's a key difference between $request->exists() and $request->has() that can save you time and hassle!

exists() vs has() in Laravel: Best Practices for Query Parameters Image

Working with HTTP requests in Laravel? Handling query parameters correctly can make your code more robust and expressive. Two handy methods on the Request object—exists() and has()—let you test parameter presence in slightly different ways. Understanding their distinction helps you avoid logical bugs and write cleaner conditionals.

1. $request->exists('key')

  • What it does: Returns true if the parameter key is present in the request payload—regardless of its value (even if it’s null or an empty string).

  • When to use:

    • You simply need to know “did the client include this parameter?”

    • You’re building features that distinguish between “parameter missing” vs. “parameter blank.”

if ($request->exists('promo_code')) {
    // promo_code key was sent, even if empty
    // maybe apply a default or log that user wanted to use a code
}

2. $request->has('key')

  • What it does: Returns true only if the parameter key is present and its value is not null. Note: an empty string '' still counts as a value, so has() returns true.

  • When to use:

    • You need a “meaningful” value to proceed.

    • You want to guard against null inputs (e.g., missing checkbox fields).

if ($request->has('newsletter')) {
    // user explicitly checked or un-checked; value might be 'on' or empty
    subscribeUser(); 
}

3. Quick Comparison Table

MethodChecks key presence?Accepts null value?Accepts empty string?
exists('key')✔️✔️✔️
has('key')✔️✔️

4. Real‑World Use Case

Imagine an API endpoint where clients can filter products:

  • exists(): Let clients pass ?on_sale (no value) to request only sale items. Your controller can check exists('on_sale') to apply the filter whether they do ?on_sale= or just ?on_sale.

  • has(): For something like ?category=electronics, use has('category') to make sure you actually have a non-null category before querying.


Conclusion
Choosing between exists() and has() is all about intention:

  • Use exists() when the mere presence of a key matters.

  • Use has() when you need a non-null value.

Happy coding! 🚀


👉 Next up on TutorialTools:

  • How to handle checkbox arrays in Laravel requests

  • Sanitizing and validating complex query parameters

Tags

Do you Like?