Vivek Mistry 👋

I’m a Certified Senior Laravel Developer with 8+ years of experience , specializing in building robust APIs and admin panels, frontend templates converting them into fully functional web applications.

Book A Call
  • 17 Jan, 2026
  • 59 Views
  • Ensure values always stay within a safe range without complex conditions.

Control Numeric Limits in Laravel Using Number::clamp()

Laravel’s Number::clamp() helper allows developers to restrict numeric values within a defined minimum and maximum range. This article explains how it works with a real-world project example for clear understanding.

Real Project Use Case: Product Quantity Control

Imagine an e-commerce project where:

  • Minimum order quantity is 1
  • Maximum allowed quantity per order is 10
  • Quantity comes from request input
use Illuminate\Support\Number;
$quantity = Number::clamp(
    request('quantity'),
    1,
    10
);

Now:

  • 0 becomes 1
  • 50 becomes 10
  • 5 stays 5

You can safely use $quantity anywhere in your order logic.


Use Case: Rating System (1 to 5 Stars)

$rating = Number::clamp($request->rating, 1, 5);

Even if a user sends -2 or 10, your system always stores a valid rating.

Use Case: Pagination Limit Protection

APIs often allow a limit parameter, but unrestricted limits can hurt performance.

$limit = Number::clamp(
    request('limit', 20),
    10,
    100
);

This guarantees:

  • No extremely small queries
  • No massive data loads
  • Predictable API behavior

Why Number::clamp() Is Better Than Conditions

Without it, you’d write something like:

if ($value < 1) {
    $value = 1;
} elseif ($value > 10) {
    $value = 10;
}

With Number::clamp():

  • Intent is obvious
  • Code is shorter
  • Logic is reusable
  • Fewer bugs over time

Share: