alihaider / flexible-boolean
Flexible boolean validation rule supporting true/false strings and values
Package info
github.com/Alihaider8014/laravel-flexible-boolean
pkg:composer/alihaider/flexible-boolean
Requires
- php: >=7.4
- illuminate/support: ^8.0 || ^9.0 || ^10.0 || ^11.0 || ^12.0 || ^13.0
Requires (Dev)
- orchestra/testbench: ^8.0
- pestphp/pest: ^2.0
- phpunit/phpunit: ^10.0
README
A powerful and flexible boolean validation rule for Laravel that supports real-world API and frontend inputs like "true" and "false".
๐ Why This Package Exists
Laravel's default boolean validation rule does NOT accept string values like:
"true""false"
However, in real-world applications (APIs, frontend forms, third-party integrations), boolean values are often sent as strings.
This package solves that problem by providing a flexible and reliable boolean validation rule.
โจ Features
- Supports:
true/false"true"/"false"1/0"1"/"0"
- Laravel validation rule
- Helper methods for conversion
- Fully testable and production ready
๐ฆ Installation
Install via Composer:
composer require AliHaider/laravel-flexible-boolean
โ๏ธ Service Provider
Laravel supports auto-discovery, so no manual registration is required.
If you are using an older Laravel version or need to register manually, add the service provider:
// config/app.php
'providers' => [ AliHaider\FlexibleBoolean\FlexibleBooleanRuleServiceProvider::class, ];
โ Usage
1. Validation Rule
$request->validate([ 'is_active' => 'required|flexible_boolean' ]);
2. Using Rule Class
use AliHaider\FlexibleBoolean\FlexibleBooleanRule; $request->validate([ 'is_active' => ['required', new FlexibleBooleanRule()], ]);
3. Convert Value to Boolean
use AliHaider\FlexibleBoolean\FlexibleBooleanRule; FlexibleBooleanRule::toBoolean('true'); // true FlexibleBooleanRule::toBoolean('false'); // false FlexibleBooleanRule::toBoolean('1'); // true FlexibleBooleanRule::toBoolean('0'); // false
โ๏ธ Comparison with Laravel Default
| Feature | Laravel Default | This Package |
|---|---|---|
Accept "true" string |
โ No | โ Yes |
Accept "false" string |
โ No | โ Yes |
| Strict boolean validation | โ Yes | โ Yes |
| API-friendly | โ Limited | โ Fully |
๐งช Example (Real-World API)
POST /api/user
{
"is_active": "true"
}
Validation:
$request->validate([ 'is_active' => 'required|flexible_boolean' ]);