PHPackages                             dev-kraken/env-validator - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. dev-kraken/env-validator

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

dev-kraken/env-validator
========================

Type-safe environment variable validation for Laravel and PHP applications with intelligent presets and extensible rule objects

V1.1.0(11mo ago)17188↓50%1[1 issues](https://github.com/dev-kraken/env-validator/issues)MITPHPPHP ^8.2CI passing

Since May 26Pushed 11mo agoCompare

[ Source](https://github.com/dev-kraken/env-validator)[ Packagist](https://packagist.org/packages/dev-kraken/env-validator)[ Docs](https://github.com/dev-kraken/env-validator)[ GitHub Sponsors](https://github.com/dev-kraken)[ RSS](/packages/dev-kraken-env-validator/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (7)Versions (3)Used By (0)

[   ![Header Image](images/header-light.png) ](https://devkraken.com/)EnvValidator
============

[](#envvalidator)

> **Type-safe environment variable validation for Laravel and PHP applications**

[![Latest Version on Packagist](https://camo.githubusercontent.com/229bead59604149834716fc8785341e3a3aa9738d01dfa1d2b4a5cdb062c59bf/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6465762d6b72616b656e2f656e762d76616c696461746f722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/dev-kraken/env-validator)[![Total Downloads](https://camo.githubusercontent.com/023e4fff0443e30b31fa70071ad7049c238f49450b94dc65d77c4477fcdd19b2/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6465762d6b72616b656e2f656e762d76616c696461746f722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/dev-kraken/env-validator)[![Build Status](https://github.com/dev-kraken/env-validator/actions/workflows/ci.yml/badge.svg)](https://github.com/dev-kraken/env-validator/actions)[![License](https://camo.githubusercontent.com/09d494c450dc5e95c4433ce0359a8937ba8461ba422ee3257c92516929baa012/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6465762d6b72616b656e2f656e762d76616c696461746f722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/dev-kraken/env-validator)[![PHP Version](https://camo.githubusercontent.com/accd9ae585851d1ae950f8ec7d36a3cd444fb287a636166567e87007d9f70c4f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f6465762d6b72616b656e2f656e762d76616c696461746f722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/dev-kraken/env-validator)[![Tests](https://camo.githubusercontent.com/f6d56b95a664b63c082190e0abf64751a22aa6ffa6e0732e90961253e159c7d7/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6465762d6b72616b656e2f656e762d76616c696461746f722f63692e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/dev-kraken/env-validator/actions)

EnvValidator is a modern, type-safe PHP package for validating environment variables in Laravel and standalone PHP applications. It provides robust validation with clear error messages, intelligent presets, extensible rule objects, and automatic environment file synchronization.

✨ Features
----------

[](#sparkles-features)

- 🔒 **Type-safe validation** with PHP 8.2+ and PHPStan level max
- 🎯 **Smart presets** for common scenarios (Laravel, microservices, production, etc.)
- 🧩 **Extensible rule system** with custom Rule objects
- 🔄 **Environment sync** to keep `.env` and `.env.example` synchronized
- 🚀 **Laravel integration** with auto-discovery and Artisan commands
- 📦 **Standalone support** for non-Laravel PHP applications
- 🛡️ **Production-ready** with comprehensive test coverage
- 📝 **Clear error messages** with detailed validation feedback

🚀 Quick Start
-------------

[](#rocket-quick-start)

### Installation

[](#installation)

```
composer require dev-kraken/env-validator
```

You can publish the configuration file with:

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

### Laravel Usage

[](#laravel-usage)

```
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();
```

### Standalone PHP Usage

[](#standalone-php-usage)

#### Basic Example (String Rules)

[](#basic-example-string-rules)

```
use EnvValidator\EnvValidator;

// Simple validation with string rules
$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";
```

#### Advanced Example (Rule Objects)

[](#advanced-example-rule-objects)

```
use EnvValidator\EnvValidator;
use EnvValidator\Collections\StringRules\{InRule, BooleanRule};
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()],
]);

// For standalone PHP, use validateStandalone method
$result = EnvValidator::validateStandalone($_ENV, $validator->getRules());

if ($result !== true) {
    // Handle validation errors
    foreach ($result as $field => $errors) {
        foreach ($errors as $error) {
            echo "Error: $error\n";
        }
    }
    exit(1);
}

echo "✅ Environment validation passed!\n";
```

### Required Field Validation

[](#required-field-validation)

EnvValidator properly handles required field validation in both Laravel and standalone PHP environments:

```
// All these formats work for required validation
$rules = [
    'APP_KEY' => ['required', 'string', 'min:32'],        // Array format (recommended)
    'APP_ENV' => 'required|string',                       // String format
    'DB_PASSWORD' => ['required'],                        // Required only
    'API_URL' => ['string', 'required', new UrlRule()],  // Required anywhere in array
];

// Standalone validation
$result = EnvValidator::validateStandalone($_ENV, $rules);

if ($result !== true) {
    // Handle validation errors
    foreach ($result as $field => $errors) {
        echo "Error in $field: " . implode(', ', $errors) . "\n";
    }
}
```

Required fields fail validation when they are:

- ❌ **Missing** from the environment
- ❌ **Empty strings** (`''`)
- ❌ **Null values**
- ✅ **Present with valid values**

📋 Built-in Rule Presets
-----------------------

[](#clipboard-built-in-rule-presets)

PresetDescriptionUse Case`laravel`Complete Laravel applicationFull-featured web applications`minimal`Essential variables onlyMicroservices, lightweight apps`production`Production-ready settingsDeployment environments`api`API-focused applicationsREST APIs, headless applications`microservice`Microservice-specificContainerized services`docker`Docker/containerized appsContainer deployments### Preset Usage Examples

[](#preset-usage-examples)

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

🎯 Rule Objects vs String Rules
------------------------------

[](#dart-rule-objects-vs-string-rules)

EnvValidator uses **Rule objects** for better type safety and maintainability:

### ✅ Rule Objects (Recommended)

[](#white_check_mark-rule-objects-recommended)

```
use EnvValidator\Collections\StringRules\{InRule, BooleanRule};
use EnvValidator\Collections\NetworkRules\UrlRule;

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

**Benefits:**

- 🔍 **IDE autocompletion** and type hints
- 🧪 **Easy unit testing** of individual rules
- ♻️ **Reusable** across multiple fields
- 🎨 **Custom error messages** with context
- 🔧 **Better debugging** and inspection

### 📚 Available Rule Objects

[](#books-available-rule-objects)

#### String Rules

[](#string-rules)

- `BooleanRule` - Validates boolean values (true, false, 1, 0, yes, no, etc.)
- `InRule` - Validates value is in a list of allowed values
- `KeyRule` - Validates Laravel application keys (base64: format)
- `PatternRule` - Validates against regex patterns
- `EmailRule` - Validates email addresses
- `JsonRule` - Validates JSON strings

#### Numeric Rules

[](#numeric-rules)

- `NumericRule` - Validates numeric values
- `IntegerRule` - Validates integer values
- `PortRule` - Validates port numbers (1-65535)

#### Network Rules

[](#network-rules)

- `UrlRule` - Validates URLs
- `IpRule` - Validates IP addresses

🛠️ Advanced Usage
-----------------

[](#hammer_and_wrench-advanced-usage)

### Custom Rules

[](#custom-rules)

```
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()]);
```

### Environment-Specific Validation

[](#environment-specific-validation)

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

### Conditional Validation

[](#conditional-validation)

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

🎨 Laravel Integration
---------------------

[](#art-laravel-integration)

### Artisan Commands

[](#artisan-commands)

```
# Validate all environment variables
php artisan env:validate

# Validate specific variables
php artisan env:validate --keys=APP_KEY --keys=APP_URL

# Verbose output with debugging info
php artisan env:validate -v
```

🔄 Environment File Synchronization
----------------------------------

[](#arrows_counterclockwise-environment-file-synchronization)

Keep your `.env` and `.env.example` files synchronized automatically! This feature helps prevent deployment issues when developers add new environment variables but forget to update the example file.

### 🔍 Check Synchronization Status

[](#mag-check-synchronization-status)

```
# Check if .env and .env.example are synchronized
php artisan env:sync --check
```

**Sample Output:**

```
🔍 Checking environment file synchronization...

⚠️  3 key(s) missing in .env.example, 1 extra key(s) in .env.example

📊 Statistics:
   • .env keys: 15
   • .env.example keys: 13

🔍 Missing in .env.example:
   📂 Sensitive:
      • STRIPE_SECRET = ********
   📂 Third party:
      • STRIPE_PUBLIC_KEY = pk_test_1234...
   📂 Application:
      • FEATURE_FLAG_NEW_UI = true

🗑️  Extra in .env.example:
   • LEGACY_API_KEY

💡 Suggestions:
   • Add missing keys to .env.example
   • Remove unused keys from .env.example

```

### ⚙️ Synchronization Commands

[](#gear-synchronization-commands)

```
# Automatically synchronize files (with confirmation)
php artisan env:sync

# Force sync without confirmation
php artisan env:sync --force

# Add keys with empty values (security-conscious)
php artisan env:sync --no-values

# Remove extra keys from .env.example
php artisan env:sync --remove-extra

# Use custom file paths
php artisan env:sync --env-path=/custom/.env --example-path=/custom/.env.example
```

### 🛡️ Security Features

[](#shield-security-features)

The sync command automatically handles sensitive data:

- **Sensitive keys** (PASSWORD, SECRET, KEY, TOKEN) get **empty values**
- **URLs** become `https://example.com`
- **Email addresses** become `user@example.com`
- **Boolean values** are standardized to `true`
- **Numeric values** (ports, timeouts) are preserved
- **Environment names** get appropriate defaults (`production`)

### 🏗️ Integration with CI/CD

[](#building_construction-integration-with-cicd)

Add environment sync checks to your deployment pipeline:

```
# In your CI/CD pipeline
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
```

### 💻 Programmatic Usage

[](#computer-programmatic-usage)

```
use EnvValidator\Services\EnvExampleSyncService;
use EnvValidator\Facades\EnvSync;

// Using the facade
$report = EnvSync::getSyncReport();
if ($report['status'] !== 'synced') {
    // Handle out-of-sync files
    $result = EnvSync::syncToExample(['generate_values' => true]);
}

// Using the service directly
$syncService = new EnvExampleSyncService();
$report = $syncService->getSyncReport();

// Check specific conditions
if ($syncService->envFileExists() && !$syncService->exampleFileExists()) {
    // Create .env.example from .env
    $syncService->syncToExample(['generate_values' => true]);
}

// Get validation rule suggestions for new keys
$comparison = $syncService->compareFiles();
$suggestedRules = $syncService->suggestValidationRules(
    $comparison['missing_in_example']
);
```

### 💻 Standalone PHP Usage

[](#computer-standalone-php-usage)

The environment sync feature works perfectly in standalone PHP applications (without Laravel):

```
use EnvValidator\Services\EnvExampleSyncService;

// IMPORTANT: Always provide explicit paths in standalone PHP
$syncService = new EnvExampleSyncService(
    __DIR__ . '/.env',           // Path to your .env file
    __DIR__ . '/.env.example'    // Path to your .env.example file
);

// Check synchronization status
$report = $syncService->getSyncReport();
if ($report['status'] !== 'synced') {
    echo "⚠️  Environment files are out of sync!\n";

    // Show what's missing
    foreach ($report['missing_in_example'] as $category => $keys) {
        echo "Missing {$category} keys: " . implode(', ', array_keys($keys)) . "\n";
    }

    // Auto-sync files
    $result = $syncService->syncToExample([
        'add_missing' => true,
        'remove_extra' => true,
        'generate_values' => true
    ]);

    if ($result['success']) {
        echo "✅ Files synchronized successfully!\n";
    }
}

// Integration with validation
$rules = [
    'APP_ENV' => 'required|string',
    'DB_HOST' => 'required|string',
    'API_KEY' => 'required|string|min:10',
];

$validationResult = EnvValidator::validateStandalone($_ENV, $rules);
if ($validationResult !== true) {
    // Handle validation errors
    foreach ($validationResult as $field => $errors) {
        echo "Error in {$field}: " . implode(', ', $errors) . "\n";
    }
}
```

#### Different Project Structures

[](#different-project-structures)

```
// Current directory
$syncService = new EnvExampleSyncService(
    getcwd() . '/.env',
    getcwd() . '/.env.example'
);

// Config directory
$syncService = new EnvExampleSyncService(
    getcwd() . '/config/.env',
    getcwd() . '/config/.env.example'
);

// Absolute paths
$syncService = new EnvExampleSyncService(
    '/var/www/app/.env',
    '/var/www/app/.env.example'
);

// Custom file names
$syncService = new EnvExampleSyncService(
    getcwd() . '/environment.conf',
    getcwd() . '/environment.example.conf'
);
```

#### Deployment Script Integration

[](#deployment-script-integration)

```
#!/usr/bin/env php
