Tools for easier boolean manipulation in Laravel.
- PHP ^8.4
- Laravel ^12|^13
composer require t-labs-co/booleanizeUpgrading from v1.x? Read the Migration Guide for a step-by-step upgrade path.
use TLabsCo\Booleanize\Facades\Booleanize;
// Convert various values to boolean
Booleanize::convert('yes'); // true
Booleanize::convert('no'); // false
Booleanize::convert('on'); // true
Booleanize::convert('off'); // false
Booleanize::convert('1'); // true
Booleanize::convert('0'); // falsebooleanize('yes'); // true
booleanize('no'); // false
// Convert arrays
booleanize(['status' => 'yes', 'active' => 'no']);
// ['status' => true, 'active' => false]The following values are recognized as true:
| Value | Type |
|---|---|
y |
string |
yes |
string |
active |
string |
enable |
string |
on |
string |
1 |
string |
true |
string |
good |
string |
ok |
string |
1 |
integer |
true |
boolean |
The following values are recognized as false:
| Value | Type |
|---|---|
n |
string |
no |
string |
inactive |
string |
disable |
string |
off |
string |
0 |
string |
false |
string |
bad |
string |
not_ok |
string |
0 |
integer |
false |
boolean |
use TLabsCo\Booleanize\Rules\BooleanizeRule;
use TLabsCo\Booleanize\Rules\BooleanizeTrueRule;
use TLabsCo\Booleanize\Rules\BooleanizeFalseRule;
$request->validate([
'status' => ['required', new BooleanizeRule],
'active' => ['required', new BooleanizeTrueRule],
'deleted' => ['required', new BooleanizeFalseRule],
]);use TLabsCo\Booleanize\Casts\BooleanizeCast;
use TLabsCo\Booleanize\Casts\BooleanizeInboundCast;
class User extends Model
{
protected $casts = [
'is_active' => BooleanizeCast::class,
'status' => BooleanizeInboundCast::class,
];
}use TLabsCo\Booleanize\Model\HasBooleanizeTrait;
class User extends Model
{
use HasBooleanizeTrait;
public function getTrueValueAs(): array
{
return [
'is_active' => 'enabled',
];
}
public function setTrueValueAs(): array
{
return [
'is_active' => 'enabled',
];
}
}
// Query scopes
User::whereBooleanizeTrue('is_active')->get();
User::whereBooleanizeFalse('is_active')->get();
User::whereBooleanize('is_active', 'enabled')->get();Booleanize::convert('yes', null, 'enabled'); // 'enabled'
Booleanize::convert('no', null, 'enabled'); // 'disabled'Booleanize::inverse('yes'); // false
Booleanize::inverse('no'); // trueBooleanize::human('yes'); // 'Yes, I agree'
Booleanize::human('no'); // 'No, I don't'Publish the config file:
php artisan vendor:publish --tag=booleanize-configcomposer test # Run Pest tests
composer analyse # Run PHPStan
composer format # Run Laravel PintThe MIT License (MIT). Please see License File for more information.