Type-Safe Environment Variable Validation in Laravel & PHP

EnvValidator is a Composer package that validates Laravel and standalone PHP .env files at boot — typed rules, presets per project shape, and a `php artisan env:sync` command that keeps .env and .env.example aligned.

Soman Bandesha Updated 8 min read
Type-Safe Environment Variable Validation in Laravel & PHP

Most production incidents I’ve watched a team chase turn out to be a missing .env key or an APP_KEY that’s the wrong length. The fix is to validate the environment before the app boots, so the deploy fails loudly instead of the app failing quietly.

EnvValidator is the PHP package I wrote for that. It runs in Laravel via a service provider, or standalone in any PHP project, and it ships with presets so you don’t write the same rules in every new repo.

What Is EnvValidator?

EnvValidator is a modern PHP package for validating environment variables in Laravel and PHP projects.

It helps developers make sure required environment variables exist, use the correct format, and match the expected type before the application runs in production.

With EnvValidator, you can:

  • Validate required environment variables
  • Use Laravel-style string validation rules
  • Use type-safe rule objects
  • Apply built-in presets for common project types
  • Keep .env and .env.example files synchronized
  • Run validation in CI/CD pipelines
  • Use the package in Laravel or standalone PHP apps

Why Environment Variable Validation Matters

Environment variables often contain critical application configuration, including:

  • Database credentials
  • Application environment settings
  • API keys
  • Mail configuration
  • Cache and queue settings
  • Third-party service credentials
  • Feature flags

Without validation, teams may only discover missing or invalid values after deployment.

This can lead to:

  • Failed deployments
  • Database connection errors
  • Broken integrations
  • Security misconfigurations
  • Debugging delays
  • Inconsistent environments across teams

EnvValidator helps catch these problems early by validating configuration before it becomes a production issue.

Key Features of EnvValidator

EnvValidator includes several features designed for real-world Laravel and PHP projects.

Type-Safe Validation

EnvValidator supports type-safe validation using modern PHP features.

You can validate values such as:

  • Strings
  • Booleans
  • URLs
  • Emails
  • JSON strings
  • Integers
  • Ports
  • IP addresses
  • Laravel application keys
  • Allowed values

This helps reduce type-related bugs and makes configuration validation more predictable.

Smart Presets

EnvValidator includes built-in presets for common application types.

Available presets include:

  • laravel
  • minimal
  • production
  • api
  • microservice
  • docker

These presets make it faster to set up validation rules for different project needs.

For example, a production application may require stricter checks, while a microservice may only need a smaller set of required variables.

Custom Rule Objects

EnvValidator supports reusable rule objects for advanced validation.

Rule objects make validation logic easier to test, reuse, and maintain. They also improve readability compared to long string-based validation rules.

This is especially useful when you need custom rules for application-specific environment variables.

Environment File Synchronization

Keeping .env and .env.example files in sync is important for team collaboration and deployment consistency.

EnvValidator can detect when keys are missing from .env.example, identify extra keys, and help generate safer example values.

This prevents situations where a developer adds a new environment variable locally but forgets to document it for the rest of the team.

Laravel Integration

EnvValidator integrates with Laravel through auto-discovery, a facade, configuration publishing, and Artisan commands.

You can validate environment variables directly from your Laravel application or from the command line.

Common commands include:

php artisan env:validate
php artisan env:sync
php artisan env:sync --check

Standalone PHP Support

EnvValidator is not limited to Laravel.

You can also use it in standalone PHP applications, making it useful for custom PHP projects, scripts, APIs, and microservices.

Installing EnvValidator

Install the package with Composer:

composer require dev-kraken/env-validator

For Laravel applications, publish the configuration file:

php artisan vendor:publish --provider="EnvValidator\EnvValidatorServiceProvider" --tag="config"

Laravel Usage

In Laravel, you can use the EnvValidator facade.

use EnvValidator\Facades\EnvValidator;

// Validate with default Laravel rules
EnvValidator::validate();

// Use production rules
EnvValidator::useProductionRules()->validate();

// Use minimal rules
EnvValidator::useMinimalRules()->validate();

// Use API-focused rules
EnvValidator::useApiRules()->validate();

This allows you to validate your environment configuration directly inside your Laravel application.

Standalone PHP Usage

EnvValidator can also validate environment variables in standalone PHP projects.

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";

This is useful for non-Laravel applications that still need reliable environment validation.

Using Rule Objects

Rule objects provide a cleaner and more type-safe way to define validation logic.

use EnvValidator\EnvValidator;
use EnvValidator\Collections\StringRules\BooleanRule;
use EnvValidator\Collections\StringRules\InRule;
use EnvValidator\Collections\NetworkRules\UrlRule;

$validator = new EnvValidator();

$validator->setRules([
    'APP_ENV' => ['required', 'string', new InRule(['staging', 'production'])],
    'APP_DEBUG' => ['required', new BooleanRule()],
    'APP_URL' => ['required', new UrlRule()],
]);

$result = EnvValidator::validateStandalone($_ENV, $validator->getRules());

Rule objects are useful because they provide:

  • Better IDE support
  • Reusable validation logic
  • Easier unit testing
  • Cleaner custom error messages
  • Better debugging and inspection

Creating Custom Rules

You can create custom rule objects by extending AbstractRule.

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_".';
    }
}

Then use the rule in your validator:

$validator->addRule('CUSTOM_FIELD', [new CustomRule()]);

Custom rules are helpful when your application has unique validation requirements.

Environment-Specific Validation

You can apply different validation rules depending on the current environment.

if (app()->environment('local', 'development')) {
    $validator->useMinimalRules();
} else {
    $validator->useProductionRules();
}

This lets you keep local development flexible while enforcing stricter validation in staging or production.

Conditional Validation

EnvValidator supports conditional validation patterns.

$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'],
];

Conditional rules are useful when certain variables are only required for specific drivers, services, or environments.

Built-In Presets

EnvValidator provides several presets for common project types.

PresetDescriptionUse Case
laravelComplete Laravel application rulesFull-featured Laravel apps
minimalEssential variables onlyLightweight apps and microservices
productionProduction-ready validationDeployment environments
apiAPI-focused rulesREST APIs and headless applications
microserviceMicroservice-specific variablesContainerized services
dockerDocker-focused configurationContainer deployments

Preset Usage Examples

use EnvValidator\EnvValidator;

// 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']);

Presets help reduce setup time while keeping validation consistent across similar projects.

Available Rule Objects

EnvValidator includes several built-in rule objects.

String Rules

  • BooleanRule validates boolean values such as true, false, 1, 0, yes, and no
  • InRule validates that a value exists in an allowed list
  • KeyRule validates Laravel application keys
  • PatternRule validates values against regular expressions
  • EmailRule validates email addresses
  • JsonRule validates JSON strings

Numeric Rules

  • NumericRule validates numeric values
  • IntegerRule validates integer values
  • PortRule validates port numbers from 1 to 65535

Network Rules

  • UrlRule validates URLs
  • IpRule validates IP addresses

Environment File Synchronization

EnvValidator can help keep .env and .env.example files synchronized.

This is especially useful in teams where multiple developers may add new environment variables over time.

Check Sync Status

php artisan env:sync --check

This checks whether .env and .env.example are synchronized without changing files.

Sync with Confirmation

php artisan env:sync

This synchronizes environment files with confirmation.

Force Sync

php artisan env:sync --force

This synchronizes files without asking for confirmation.

Redact Sensitive Values

php artisan env:sync --no-values

This adds missing keys without copying sensitive values.

Remove Extra Keys

php artisan env:sync --remove-extra

This removes extra keys from .env.example.

Use Custom File Paths

php artisan env:sync --env-path=/custom/.env --example-path=/custom/.env.example

This is useful when your environment files are stored in non-standard locations.

CI/CD Integration

EnvValidator can be used in CI/CD pipelines to prevent broken deployments.

php artisan env:sync --check

if [ $? -ne 0 ]; then
    echo "❌ Environment files are out of sync!"
    echo "Run 'php artisan env:sync' to fix."
    exit 1
fi

You can also run validation before deployment to make sure required variables are present and valid.

php artisan env:validate

If validation fails, the pipeline can stop before the application reaches production.

Security Benefits

EnvValidator helps improve configuration security by:

  • Detecting missing sensitive variables
  • Redacting sensitive values in example files
  • Preventing secrets from being copied into .env.example
  • Encouraging documented environment configuration
  • Making production checks easier to automate

During synchronization, sensitive keys such as passwords, secrets, tokens, and keys can be replaced with safe placeholder values.

Common Use Cases

EnvValidator is useful for:

  • Laravel applications
  • Standalone PHP projects
  • APIs
  • Microservices
  • Dockerized applications
  • CI/CD pipelines
  • Team-based development
  • Production deployments

It helps teams avoid broken deployments caused by missing or undocumented environment variables.

Frequently Asked Questions

Is EnvValidator only for Laravel?

No. EnvValidator supports both Laravel and standalone PHP applications.

Can I define custom validation rules?

Yes. You can create custom rule objects by extending AbstractRule.

Does EnvValidator support CI/CD?

Yes. You can use commands like php artisan env:validate and php artisan env:sync --check inside deployment pipelines.

How does EnvValidator handle sensitive variables?

During environment sync, sensitive values can be redacted or replaced with safe placeholders so secrets are not exposed in .env.example.

Does it support different environments?

Yes. You can conditionally apply presets or custom rules based on environments such as local, staging, testing, or production.

Wrap-up

The point of validating .env at boot is to turn a midnight pager into a CI failure. EnvValidator does it with typed rules in PHP, a Laravel facade if you want one, presets per project shape, and a sync command so .env.example stops drifting from .env.

Repo, issues, and install instructions: github.com/dev-kraken/env-validator.