Laravel Tutorials

Enhancing Numeric Validation with Laravel's Fluent Rule Interface

Published
Enhancing Numeric Validation with Laravel's Fluent Rule Interface image

Laravel introduces a more expressive approach to numeric validation through the fluent Rule::numeric() interface. This syntax transforms traditional string-based rules into chainable methods for improved readability.

The implementation provides a more developer-friendly syntax:

// Before
$rules = [
    'price' => 'numeric|min:5|max:1000|decimal:2',
];

// After
$rules = [
    'price' => Rule::numeric()
        ->min(5)
        ->max(1000)
        ->decimal(2),
];

This approach particularly shines when implementing comprehensive validation for financial or measurement data:

class ProductController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'price' => Rule::numeric()
                ->min(0.01)
                ->max(9999.99)
                ->decimal(2),
            'weight' => Rule::numeric()
                ->min(0)
                ->decimal(3)
                ->nullable(),
            'stock' => Rule::numeric()
                ->integer()
                ->min(0)
                ->nullable(),
            'discount_percent' => Rule::numeric()
                ->between(0, 100)
                ->decimal(1)
        ]);
        
        Product::create($validated);
        
        return redirect()->route('products.index')
            ->with('success', 'Product created successfully');
    }
}

The fluent numeric validation interface creates more maintainable rule definitions while providing better IDE support through method chaining rather than string parsing.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

serpapi logo
SerpApi

The Web Search API for Your LLM and AI Applications

Visit SerpApi

The latest

View all →
PHP 8.6 is released!  image

PHP 8.6 is released!

Read article
Laravel Warrant: Row-Level Permissions With Eloquent image

Laravel Warrant: Row-Level Permissions With Eloquent

Read article
JSON Schema Validation Rules and a RetryFor Attribute in Laravel 13.43 image

JSON Schema Validation Rules and a RetryFor Attribute in Laravel 13.43

Read article
Durable Workflow: Long-Running Workflows for Laravel image

Durable Workflow: Long-Running Workflows for Laravel

Read article
Session Replay for Laravel: Self-Hosted Browser Recordings image

Session Replay for Laravel: Self-Hosted Browser Recordings

Read article
Laravel AI SDK 1.4 Lets Agents Recover From Tool Failures image

Laravel AI SDK 1.4 Lets Agents Recover From Tool Failures

Read article