Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Config Validator Laravel Package

ashallendesign/laravel-config-validator

Validate your Laravel config at runtime or via Artisan. Define rulesets for config files with custom messages and environment targeting, generate rulesets quickly, and optionally publish defaults. Catch missing/invalid config early in local, CI, or production.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ashallendesign/laravel-config-validator
    

    Publish the default ruleset configuration:

    php artisan vendor:publish --provider="AshAllenDesign\ConfigValidator\ConfigValidatorServiceProvider" --tag="config-validator-rulesets"
    
  2. First Use Case: Define a validation rule in config/config-validator.php:

    'rulesets' => [
        'app' => [
            'env' => ['required', 'in:local,staging,production'],
            'debug' => ['boolean'],
        ],
    ],
    

    Run validation in a command, service provider, or route:

    use AshAllenDesign\ConfigValidator\Facades\ConfigValidator;
    
    ConfigValidator::validate('app');
    

Where to Look First

  • Configuration File: config/config-validator.php (published rulesets).
  • Facade: ConfigValidator for quick validation calls.
  • Artisan Command: php artisan config:validate for CLI validation.

Implementation Patterns

Core Workflows

  1. Validation in Bootstrapping: Add validation to AppServiceProvider’s boot() method to fail fast during application startup:

    public function boot()
    {
        if (!ConfigValidator::validate('app')) {
            exit(1); // Or throw an exception
        }
    }
    
  2. Dynamic Rulesets: Load rulesets conditionally (e.g., based on environment):

    $ruleset = config('app.env') === 'local' ? 'local' : 'production';
    ConfigValidator::validate($ruleset);
    
  3. Custom Rules: Extend validation with custom rules by implementing AshAllenDesign\ConfigValidator\Contracts\Rule:

    use AshAllenDesign\ConfigValidator\Contracts\Rule;
    
    class IsNonEmptyArray implements Rule
    {
        public function __invoke($value, $attribute, $config)
        {
            return is_array($value) && !empty($value);
        }
    }
    

    Register the rule in config/config-validator.php:

    'rules' => [
        'is_non_empty_array' => \App\Rules\IsNonEmptyArray::class,
    ],
    
  4. Validation in Tests: Use in phpunit.xml or test setup:

    public function setUp(): void
    {
        $this->assertTrue(ConfigValidator::validate('test'));
    }
    

Integration Tips

  • Environment-Specific Validation: Combine with .env validation (e.g., vlucas/phpdotenv) to ensure consistency.
  • CI/CD Pipelines: Add php artisan config:validate as a pre-deploy step to catch misconfigurations early.
  • Dynamic Rulesets from Database: Fetch rulesets from a DB table and validate dynamically:
    $ruleset = DB::table('config_rulesets')->where('name', 'api')->first();
    ConfigValidator::validate(json_decode($ruleset->rules, true));
    

Gotchas and Tips

Common Pitfalls

  1. Overly Strict Rules: Avoid validating app.key or sensitive values in production rulesets—use environment-specific rulesets instead.

    // ❌ Bad: Hardcoded in 'app' ruleset
    'app.key' => ['required', 'string'],
    
    // ✅ Good: Environment-specific
    'production' => [
        'app.key' => ['required', 'string', 'size:32'],
    ],
    
  2. Circular Dependencies: Rules referencing other config values (e.g., mail.driver depending on services.mailgun.key) may cause infinite loops. Use lazy validation or separate rulesets.

  3. Silent Failures: By default, validation throws exceptions. To suppress exceptions and return a boolean:

    ConfigValidator::validate('app', false); // Second arg = throw_exception
    

Debugging Tips

  • Detailed Errors: Enable verbose output for debugging:

    ConfigValidator::validate('app', false, true); // Third arg = verbose
    

    Outputs a structured error message with failed rules.

  • Log Validation Results: Wrap validation in a try-catch to log failures:

    try {
        ConfigValidator::validate('app');
    } catch (\AshAllenDesign\ConfigValidator\Exceptions\ConfigValidationException $e) {
        \Log::error('Config validation failed: ' . $e->getMessage());
    }
    

Extension Points

  1. Custom Validators: Extend the Validator class to add pre/post-validation logic:

    use AshAllenDesign\ConfigValidator\Validator;
    
    class CustomValidator extends Validator
    {
        protected function preValidate(array $config, array $rules)
        {
            // Add logic before validation
        }
    }
    

    Bind the custom validator in the service provider:

    $this->app->bind(
        \AshAllenDesign\ConfigValidator\Contracts\Validator::class,
        \App\Validators\CustomValidator::class
    );
    
  2. Rule Caching: Cache compiled rulesets for performance (e.g., in boot()):

    if (!cache()->has('config-validator-rules')) {
        cache()->put('config-validator-rules', ConfigValidator::getRulesets());
    }
    
  3. Conditional Rules: Use PHP callbacks for dynamic rules:

    'database.connections.mysql.host' => function ($value, $config) {
        return $config['app.env'] === 'production' ? 'required' : 'nullable';
    },
    

Configuration Quirks

  • Ruleset Inheritance: Rulesets can inherit from others using the extends key:
    'rulesets' => [
        'base' => [...],
        'production' => [
            'extends' => 'base',
            'app.debug' => ['boolean', 'false'],
        ],
    ],
    
  • Nested Arrays: Validate nested config arrays with dot notation:
    'services.mailgun.key' => ['required', 'string'],
    'services.mailgun.settings' => [
        '*.timeout' => ['integer', 'between:1,30'],
    ],
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours