EnvValidator helps validate environment variables in Laravel & PHP with type safety, smart presets, and CI/CD support for secure, production-ready apps.
Dev Kraken
Environment variables are the backbone of configuration in modern web applications. They hold critical information such as database credentials, API keys, and other sensitive data. Ensuring these variables are correctly set is paramount to the application's stability and security. Misconfigured environment variables can lead to unexpected behaviors, security vulnerabilities, and application downtime
In Laravel and PHP applications, managing environment variables can become cumbersome, especially when working in teams or deploying across multiple environments. Without proper validation, it's easy to overlook missing or incorrectly set variables, leading to runtime errors that are hard to trace.
EnvValidator is a modern, type-safe PHP package designed to validate environment variables in Laravel and standalone PHP applications. It offers robust validation with clear error messages, intelligent presets, extensible rule objects, and automatic environment file synchronization. With EnvValidator, developers can ensure that their applications are correctly configured before deployment, reducing the risk of runtime errors and improving overall application stability.
EnvValidator leverages the latest features of PHP 8.2 to provide type-safe validation. It ensures that environment variables conform to the expected data types, reducing the likelihood of type-related errors. By integrating with PHPStan at the maximum level, EnvValidator offers static analysis capabilities that catch potential issues during development, leading to more robust and reliable applications.
EnvValidator comes with intelligent presets tailored for common scenarios such as Laravel applications, microservices, production environments, and more. These presets provide a set of predefined validation rules that cater to specific use cases, allowing developers to quickly set up environment validation without writing extensive custom rules.
For instance, the laravel
preset includes all the necessary environment variables for a typical Laravel application, while the production
preset focuses on variables critical for a production environment. These presets streamline the validation process and ensure consistency across different environments.
EnvValidator features an extensible rule system that allows developers to define custom validation rules using Rule objects. These objects encapsulate specific validation logic, making it easy to reuse and maintain complex validation rules. Developers can create custom Rule objects to handle unique validation requirements, enhancing the flexibility and scalability of the validation process.
For example, a custom Rule object can be created to validate that a specific environment variable starts with a particular prefix or matches a complex pattern. This modular approach to validation promotes code reuse and simplifies the management of validation logic.
Keeping .env
and .env.example
files in sync is crucial for team collaboration and deployment consistency. EnvValidator includes a powerful environment file synchronization feature that automatically detects discrepancies between these files. It identifies missing or extra keys and provides suggestions to resolve the differences, ensuring that all necessary environment variables are documented and up-to-date.
The synchronization feature also handles sensitive data appropriately by replacing values with placeholders in the .env.example
file. This prevents accidental exposure of sensitive information while maintaining a comprehensive list of required environment variables.
EnvValidator seamlessly integrates with Laravel, offering auto-discovery and a suite of Artisan commands for environment validation and synchronization. Developers can use commands like php artisan env:validate
to validate environment variables or php artisan env:sync
to synchronize .env
files. This tight integration simplifies the validation process and enhances the developer experience within Laravel applications.
Beyond Laravel, EnvValidator supports standalone PHP applications, making it a versatile tool for various PHP projects. Developers can utilize EnvValidator's validation and synchronization features without relying on the Laravel framework. This flexibility allows for consistent environment variable management across different types of PHP applications.
EnvValidator is production-ready, backed by comprehensive test coverage that ensures its reliability and stability. The package undergoes rigorous testing to validate its functionality across different scenarios and environments. This commitment to quality makes EnvValidator a dependable choice for managing environment variables in critical applications.
When validation fails, EnvValidator provides clear and detailed error messages that pinpoint the exact issues with environment variables. This feedback includes information about missing variables, incorrect data types, and other validation errors, enabling developers to quickly identify and resolve configuration problems.
To install EnvValidator, use Composer:
composer require dev-kraken/env-validator
For Laravel applications, publish the configuration file:
php artisan vendor:publish --provider="EnvValidator\EnvValidatorServiceProvider" --tag="config"
In Laravel, EnvValidator can be used through its facade:
use EnvValidator\Facades\EnvValidator;
// Validate with default Laravel rules
EnvValidator::validate();
// Use preset for different scenarios
EnvValidator::useProductionRules()->validate();
EnvValidator::useMinimalRules()->validate();
EnvValidator::useApiRules()->validate();
For standalone PHP applications, EnvValidator can be utilized as follows:
use EnvValidator\EnvValidator;
$rules = [
'APP_ENV' => 'required|string',
'APP_DEBUG' => 'required|boolean',
'APP_URL' => 'required|url',
'DB_HOST' => 'required|string',
'DB_PASSWORD' => 'required|string',
];
$result = EnvValidator::validateStandalone($_ENV, $rules);
if ($result !== true) {
echo "❌ Environment validation failed:\n";
foreach ($result as $field => $errors) {
foreach ($errors as $error) {
echo " • $error\n";
}
}
exit(1);
}
echo "✅ Environment validation passed!\n";
Developers can create custom Rule objects to handle specific validation logic:
use EnvValidator\Core\AbstractRule;
class CustomRule extends AbstractRule
{
public function passes($attribute, $value): bool
{
return str_starts_with($value, 'custom_');
}
public function message(): string
{
return 'The :attribute must start with "custom_".';
}
}
// Usage
$validator->addRule('CUSTOM_FIELD', [new CustomRule()]);
EnvValidator allows for environment-specific validation:
if (app()->environment('local', 'development')) {
$validator->useMinimalRules();
} else {
$validator->useProductionRules();
}
Conditional validation rules can be defined using Laravel's validation syntax:
$rules = [
'DB_HOST' => ['required_unless:DB_CONNECTION,sqlite', 'string'],
'DB_PORT' => ['required_unless:DB_CONNECTION,sqlite', new PortRule()],
'REDIS_HOST' => ['required_if:CACHE_DRIVER,redis', 'string'],
];
EnvValidator provides several built-in presets tailored for common project scenarios:
laravel
– Designed for complete Laravel applications.minimal
– Includes only essential environment variables.production
– Optimized for production-ready settings.api
– Focused on API-driven applications.microservice
– Tailored for microservice environments.docker
– Geared towards Docker and containerized applications.// Laravel application
$validator = (new EnvValidator())->usePreset('laravel');
// Microservice
$validator = (new EnvValidator())->usePreset('microservice');
// Production deployment
$validator = (new EnvValidator())->useProductionRules();
// Custom combination
$validator = (new EnvValidator())
->useMinimalRules()
->addRule('CUSTOM_API_KEY', ['required', 'string', 'min:32']);
Using Rule objects offers several advantages:
String Rules
BooleanRule
: Validates boolean values (true, false, 1, 0, yes, no, etc.)InRule
: Validates valueManaging environment files like .env
and .env.example
across teams and deployment environments can be error-prone. EnvValidator simplifies this with its powerful sync feature, ensuring consistency and preventing missed or outdated configuration keys.
.env
and .env.example
php artisan env:sync --check
php artisan env:sync
php artisan env:sync --force
php artisan env:sync --no-values
.env.example
:php artisan env:sync --remove-extra
php artisan env:sync --env-path=/custom/.env --example-path=/custom/.env.example
php artisan env:sync --check
if [ $? -ne 0 ]; then
echo "❌ .env files are out of sync!"
exit 1
fi
1. Is EnvValidator only for Laravel?
No, it also supports standalone PHP applications without any Laravel dependencies.
2. How does EnvValidator handle sensitive variables?
During sync, sensitive keys are redacted with placeholders in .env.example
to protect secrets.
3. Can I define custom validation rules?
Yes! You can extend the AbstractRule
class to create fully custom rule logic.
4. What happens if validation fails in CI/CD?
You can configure your pipeline to fail the deployment if .env
files are out of sync or invalid.
5. Does it support different environments like staging or testing?
Yes, you can conditionally apply presets or custom rules based on the environment context.
EnvValidator is more than just a validator—it's a developer-first toolkit designed to ensure your Laravel and PHP environments are always production-ready, secure, and well-documented. Whether you're building a monolith, a microservice, or a Dockerized API, EnvValidator's flexible rule system and powerful sync feature make it an essential part of your deployment strategy.