A Laravel package that allows you to validate your config values and environment.

Overview

Latest Version on Packagist Build Status Total Downloads PHP from Packagist GitHub license

Table of Contents

Overview

A Laravel package that allows you to validate your config values and environment.

Installation

Requirements

The package has been developed and tested to work with the following minimum requirements:

  • PHP 8.0
  • Laravel 8

Install the Package

You can install the package via Composer:

composer require ashallendesign/laravel-config-validator

Publishing the Default Rulesets

To get you started with validating your app's config, Laravel Config Validator comes with some default rulesets. To start using these rulesets, you can publish them using the following command:

php artisan vendor:publish --tag=config-validator-defaults

The above command will copy the validation files and place in a config-validation folder in your project's root. These rules are just to get you started, so there are likely going to be rule in the files that don't apply to your app. So, once you've published them, feel free to delete them or edit them as much as you'd like.

Usage

Creating a Validation Ruleset

Using the Generator Command

This package comes with a command that you can use to quickly create a validation file to get you started right away. Lets say that you wanted to create a validation file for validating the config in the config/app.php file. To do this, you could use the following command:

php artisan make:config-validation app

Running the above command would create a file in config-validation/app.php ready for you to start adding your config validation.

Ruleset Location

To validate your application's config, you need to define the validation rules first. You can do this by placing them inside files in a config-validation folder with names that match the config file you're validating. As an example, to validate the config/app.php config file, you would create a new file at config-validation/app.php that would hold the rules.

Adding Rules to a Ruleset

Once you have your ruleset file created in the config-validation folder, you can start adding your validation rules.

Under the hood, Laravel Config Validator uses the built-in Validator class, so it should seem pretty familiar to work with. To check out the available Laravel validation rules that can be used, click here.

As an example, we might want to add a config validation rule to ensure that the driver field in the app/mail.php file is a supported field. To do this, we could create a file at config-validation/mail.php with the following:



use AshAllenDesign\ConfigValidator\Services\Rule;

return [
    Rule::make('driver')->rules(['in:smtp,sendmail,mailgun,ses,postmark,log,array']),
    // ...
];

Custom Validation Error Messages

There may be times when you want to override the error message for a specific validation rule. This can be done by passing in an array containing the messages to the ->messages() method for a Rule. This array should follow the same pattern that would be used in a standard Laravel Validator object.

As an example, we might want to add a config validation rule to ensure that the driver field in the app/mail.php file is a supported field and also use a custom error message. To do this, we could update our validation file to the following:



use AshAllenDesign\ConfigValidator\Services\Rule;

return [
    Rule::make('driver')
        ->rules(['in:smtp,sendmail,mailgun,ses,postmark,log,array'])
        ->messages(['in' => 'The mail driver is invalid']),
    // ...
];

Only Running in Specific App Environments

You might not always want the same rule to be run in different environments. For example, you might want to have a relaxed set of validation rules for your local development environment and have a stricter set of rules for production.

To explicitly specify the environment that a rule can be run in, you can use the ->environments() method. If no environment is defined, the rule will be run in all environments.

The following example shows how you could set 2 different rules, one for production and one for local:



use AshAllenDesign\ConfigValidator\Services\Rule;

return [
    Rule::make('driver')
        ->rules(['in:smtp,sendmail,mailgun,ses,postmark,log,array'])
        ->environments([Rule::ENV_LOCAL]),
    
    Rule::make('driver')
        ->rules(['in:mailgun'])
        ->environments([Rule::ENV_PRODUCTION])
];

Running the Validation

Running the Validation Manually

To run the config validation you can call the ->run() method on a ConfigValidator object. The example below shows how you could do this in a controller:


    
namespace App\Http\Controllers;

use AshAllenDesign\ConfigValidator\Services\ConfigValidator;

class TestController extends Controller
{
    public function index()
    {
        $configValidator = new ConfigValidator();

        $configValidator->run();

        return response()->json(['success' => true]);
    }
}
Only Running on Selected Config Files

You might not always want to validate all of the config values in your application. So, you can specify the config files that you want to validate by passing the config names to the ->run() method as the first parameter. As an example, if you only wanted to validate the auth.php config file, you could use the following:

$configValidator = new ConfigValidator();

$configValidator->run(['auth']);
Custom Folder Path

If you aren't storing your validation files in the default config/validation folder, you can pass a custom folder path into the ->run() method as the second parameter. As an example, if you had the files stored in a app/Custom/Validation folder, you could use the following:

$configValidator = new ConfigValidator();

$configValidator->run([], 'app/Custom/Validation');

Using the Command

The library comes with a useful command that you can use to validate your config. To use it, you can run the following in the command line:

php artisan config:validate
Only Running on Selected Config Files (Command)

You might not always want to validate all of the config values in your application. So, you can specify the config files that you want to validate in the command using the --files option. As an example, if you only wanted to validate the auth.php config file, you could use the following:

php artisan config:validate --files=auth

As a further example, if you wanted to validate the auth.php and app.php files, you could use the following:

php artisan config:validate --files=auth,app
Custom Folder Path (Command)

If you aren't storing your validation files in the default config/validation folder, you can pass a custom folder path into the --path option. As an example, if you had the files stored in a app/Custom/Validation folder, you could use the following:

php artisan config:validate --path=app/Custom/Validation

Using a Service Provider

You might want to run the config validator automatically on each request to ensure that you have the correct config. This can be particularly useful if you are in a local environment and switching between Git branches often. However, you might not want it to always run automatically in production for performance reasons. To run the validation automatically on each request, you can add it to the boot method of a service provider.

The example below shows how to only run the validation in the local environment using the AppServiceProvider:



namespace App\Providers;

use AshAllenDesign\ConfigValidator\Services\ConfigValidator;
use Illuminate\Support\Facades\App;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(ConfigValidator $configValidator)
    {
        if (App::environment() === 'local') {
            $configValidator->run();
        }
    }
}

Throwing and Preventing Exceptions

By default, the ConfigValidator will throw an InvalidConfigValueException exception if the validation fails. The exception will contain the error message of the first config value that failed the validation. You can prevent the exception from being thrown and instead rely on the boolean return value of the ->run() method by using the ->throwExceptionOnFailure() method.

By preventing any exceptions from being thrown, it makes it easier for you to get all the failed validation errors using the ->errors() method. This will return the errors as an array.

The example belows shows how you could prevent any exceptions from being thrown so that you can grab the errors:

$configValidator = new ConfigValidator();

$configValidator->throwExceptionOnFailure(false)
                ->run();

$errors = $configValidator->errors();

Facade

If you prefer to use facades in Laravel, you can choose to use the provided ConfigValidator facade instead of instantiating the AshAllenDesign\ConfigValidator\Classes\ConfigValidator class manually.

The example below shows an example of how you could use the facade to run the config validation:


    
namespace App\Http\Controllers;

use ConfigValidator;

class TestController extends Controller
{
    public function index()
    {
        ConfigValidator::run();

        return response()->json(['success' => true]);
    }
}

Security

If you find any security related issues, please contact me directly at [email protected] to report it.

Contribution

If you wish to make any changes or improvements to the package, feel free to make a pull request.

Note: A contribution guide will be added soon.

Changelog

Check the CHANGELOG to get more information about the latest changes.

Upgrading

Check the UPGRADE guide to get more information on how to update this library to newer versions.

License

The MIT License (MIT). Please see License File for more information.

Comments
  • Alternative config storage

    Alternative config storage

    Hi! First of all I want to say thanks so much your job and this package. I have a problem with path configuration data. By default laravel storage data 'config' path, it's ok for everyone, but in my case complicated. I want to set data another path For example 'app/Configuration/...' I suggest changing hydrateConfigValueArray or another part codes. Inject some interface for storing configuration data, which knows how get any values. What do you think about this thought? I will make PR, if you like this idea.

    opened by agoalofalife 5
  • disable config validator temporary

    disable config validator temporary

    I get errors by start run Laravel Dusk in a local environment Is there a possibility to deactivate config validator temporary without remove from composer.json? Or Did I have configure dusk ?

    The config is correct but changed while dusk runs $php artisan dusk Environment modified. Restarting server... .... Environment modified. Restarting server...

    failure-Tests_Browser_DebugTest_testRidirect-0

    opened by erth5 4
  • Check for missing validations

    Check for missing validations

    Add missing config validations User case: when I change or add certain config keys there was no check if the config validation has been updated. With this PR the keys are checked if there is a matching config validation rule

    This PR add the functionality to test if all local config values have a config-validation rule. If not an error is reported. This can be turned off with the --skip-missing flag in the command

    opened by yormy 3
  • Crash when config value should be an array

    Crash when config value should be an array

    In my application config, I have a config item that needs to be an array of values, with at least one value in it:

    'names' => array_filter(explode(',', env('NAMES', ''))),
    

    I wanted to create a validation rule for it like this:

    Rule::make('migrate_from')->rules(['array', 'min:1']),
    

    When I run config:validate, I get this exception:

    
       Illuminate\View\ViewException 
    
      htmlspecialchars(): Argument #1 ($string) must be of type string, array given (View: /path/to/app/vendor/ashallendesign/laravel-config-validator/resources/views/validate-config.blade.php)
    
      at /path/to/app/vendor/illuminate/support/helpers.php:119
        115▕         if ($value instanceof Htmlable) {
        116▕             return $value->toHtml();
        117▕         }
        118▕
      ➜ 119▕         return htmlspecialchars($value ?? '', ENT_QUOTES, 'UTF-8', $doubleEncode);
        120▕     }
        121▕ }
        122▕
        123▕ if (! function_exists('env')) {
    
      1   /path/to/app/vendor/illuminate/view/Engines/PhpEngine.php:60
          Illuminate\View\Engines\CompilerEngine::handleViewException(Object(TypeError))
    
      2   /path/to/app/vendor/illuminate/support/helpers.php:119
          TypeError::("htmlspecialchars(): Argument #1 ($string) must be of type string, array given")
    

    I traced this to this line in the view:

    <b>{{ config($configField) }}</b>
    

    To make it work, I replaced that line with this:

    <b>{{ json_encode(config($configField, JSON_PRETTY_PRINT)) }}</b>
    

    I'm not sure whether my fix is a good way to do it (and I would submit it as a PR), or whether there is a better way. On one hand, this way will always work and will show a nice output for all kinds of config values (including simple and associative arrays). On the other hand, it changes how regular string values appear (by putting quotes around them).

    Thoughts?

    opened by kohenkatz 3
  • feat: Improve validation error styling with `Termwind`.

    feat: Improve validation error styling with `Termwind`.

    This PR adds an improvement to the output command php artisan config:validate.

    image

    Let me know what do you think.

    PS: Found an issue that I did not look for it on this PR, on the error description looks like the "_" are missing from the configField.

    opened by xiCO2k 3
  • Allow Rule objects to be used

    Allow Rule objects to be used

    Add the moment, rules can only be passed in as a string (example - required). We will also need the functionality to handle Rule objects.

    https://laravel.com/docs/8.x/validation#using-rule-objects

    opened by ash-jc-allen 3
  • Add custom messages for the validation rules

    Add custom messages for the validation rules

    Provide the option to pass custom messages into the Rule object when building it. This might be needed in places where developers don't want to rely on the default Laravel validation messages.

    opened by ash-jc-allen 1
  • Missing rules

    Missing rules

    Is it possible to thow an exception on missing validation rules. This ensures that all keys have some validations set and that not keys have been added accidentaly that have no rules set

    opened by robov 0
  • Removed illuminate/cache and required illuminate/command

    Removed illuminate/cache and required illuminate/command

    The composer.json file contained a requirement for illuminate/cache. However, this package doesn't interact with the cache, so it's not needed.

    I've also added a requirement for the illuminate/command package because we directly interact with Laravel commands.

    opened by ash-jc-allen 0
Releases(v2.3.0)
  • v2.3.0(Oct 17, 2022)

    What's Changed

    • Fixed sample code for getting validation errors by @Sy-Dante in https://github.com/ash-jc-allen/laravel-config-validator/pull/50
    • Added support for PHP 8.2 by @ash-jc-allen in https://github.com/ash-jc-allen/laravel-config-validator/pull/58

    New Contributors

    • @Sy-Dante made their first contribution in https://github.com/ash-jc-allen/laravel-config-validator/pull/50

    Full Changelog: https://github.com/ash-jc-allen/laravel-config-validator/compare/v2.2.0...v2.3.0

    Source code(tar.gz)
    Source code(zip)
  • v2.2.0(May 25, 2022)

    What's Changed

    • Require illuminate/validation and illuminate/view by @kohenkatz in https://github.com/ash-jc-allen/laravel-config-validator/pull/49
    • Fixed bug that threw an error if the failed config field was an array by @ash-jc-allen in https://github.com/ash-jc-allen/laravel-config-validator/pull/48

    New Contributors

    • @kohenkatz made their first contribution in https://github.com/ash-jc-allen/laravel-config-validator/pull/49

    Full Changelog: https://github.com/ash-jc-allen/laravel-config-validator/compare/v2.1.0...v2.2.0

    Source code(tar.gz)
    Source code(zip)
  • v2.1.0(Apr 2, 2022)

    Added

    • Improved command output using Termwind. Huge thanks to @xiCO2k for this! #38
    • Added dependency requirement for illuminate/command. #40

    Updated

    • Removed unneeded illuminate/cache dependency requirement. #40
    • Removed old and unneeded exceptions. #39
    • Updated the PHPUnit config file to the newest format. #45

    Fixed

    • Fixed bug that was removing underscores from validation error messages. #43
    Source code(tar.gz)
    Source code(zip)
  • v2.0.0(Mar 23, 2022)

    Added

    • Added support for Laravel 9 and PHP 8.1. #32
    • Added Larastan workflow to run on GitHub Actions. #34
    • Added type hints and fields types. #35

    Changed

    • Changed default directory from config/validation to config-validation. #31
    • Migrated from TravisCI to GitHub Actions for running tests. #35
    • Moved default config rulesets to stubs/config-validation. #36
    • Fixed bug that prevented Rule objects from being used. #33

    Removed

    • Dropped support for Laravel 6 and 7. #32
    • Dropped support for PHP 7.3 and 7.4. #32
    Source code(tar.gz)
    Source code(zip)
  • v1.3.0(Dec 6, 2020)

  • v1.2.0(Nov 6, 2020)

    New Features

    Added default config rulesets that can be published. (#26)

    As of Laravel Config Validator v1.2.0, the package now comes with some default rulesets. To start using these rulesets, you can publish them using the following command:

    php artisan vendor:publish --tag=config-validator-defaults
    

    The above command will copy the validation files and place them in a config/validation folder in your project. These rules are just to get you started, so there are likely going to be rules in the files that don't apply to your app. So, once you've published them, feel free to delete them or edit them as much as you'd like.

    Source code(tar.gz)
    Source code(zip)
  • v1.1.0(Oct 28, 2020)

    New Features

    Added a new errors() method to the ConfigValidator class (#22)

    A new errors() method has now been added to the ConfigValidator class and can be used for getting any errors caught during the validation. The errors are returned as an array.

    Added a new throwExceptionOnFailure() method to the ConfigValidator class (#23)

    A new throwExceptionOnFailure() method has now been added to the ConfigValidator class and can be used for determining whether if exceptions should be thrown if the validation fails.

    The example below shows how to prevent any exceptions from being thrown if the validation fails:

    $configValidator = new ConfigValidator();
    
    $errors = $configValidator->throwExceptionOnFailure(false)
                    ->run()
                    ->errors();
    

    Updated the validation console command output (#24)

    The config:validate command has been updated to make use of the new errors() and throwExceptionOnFailure() methods. Now, instead of a single validation error being returned as an exception, all of the validation error messages will be displayed in the console within a table.

    Source code(tar.gz)
    Source code(zip)
Owner
Ash Allen
Laravel Web Developer Preston, United Kingdom
Ash Allen
Update multiple Laravel Model records, each with it's own set of values, sending a single query to your database!

Laravel Mass Update Update multiple Laravel Model records, each with its own set of values, sending a single query to your database! Installation You

Jorge González 88 Dec 31, 2022
🛂 Use this package to validate the identity card from your country using laravel validation rules.

Identity Card Checker Laravel Validation Rules Use this package to validate the identity card number from your country Installation You can install th

David Torralbo Pérez 13 Feb 8, 2022
Laravel package to generate and to validate a UUID according to the RFC 4122 standard. Only support for version 1, 3, 4 and 5 UUID are built-in.

Laravel Uuid Laravel package to generate and to validate a universally unique identifier (UUID) according to the RFC 4122 standard. Support for versio

Christoph Kempen 1.7k Dec 28, 2022
Otpify is a Laravel package that provides a simple and elegant way to generate and validate one time passwords.

Laravel Otpify ?? Introduction Otpify is a Laravel package that provides a simple and elegant way to generate and validate one time passwords. Install

Prasanth Jayakumar 2 Sep 2, 2022
A laravel Livewire Dynamic Selects with multiple selects depending on each other values, with infinite levels and totally configurable.

Livewire Combobox: A dynamic selects for Laravel Livewire A Laravel Livewire multiple selects depending on each other values, with infinite levels of

Damián Aguilar 25 Oct 30, 2022
Automatically encrypt and decrypt Laravel 5 Eloquent values

Eloquent Encryption/Decryption for Laravel 5 Automatically encrypt and decrypt Laravel 5 Eloquent values. READ THIS FIRST Encrypted values are usually

Del 85 Mar 19, 2022
A simple laravel package to validate console commands arguments and options.

Command Validator A simple laravel package to validate console commands arguments and options. Installation Require/Install the package using composer

Touhidur Rahman 20 Jan 20, 2022
Vandar Cashier is a Laravel package that allows you to seamlessly implement IPG and Direct Debit on your application

Vandar Cashier is a Laravel package that provides you with a seamless integration with Vandar services. Take a look at Vandar Documentation for more i

Vandar 11 Dec 14, 2022
Generate random typed values and in any shape.

PHP Typed Generators Description Generate random typed values and in any shape. Useful for writing your tests, there's no need to write static set of

(infinite) loophp 2 Jun 8, 2022
This package allows you to easily track your laravel jobs!

Trackable Jobs For Laravel This package allows you to track your laravel jobs! Using this package, you can easily persist the output and the status of

Mateus Junges 220 Dec 25, 2022
This package provides a Logs page that allows you to view your Laravel log files in a simple UI

A simplistics log viewer for your Filament apps. This package provides a Logs page that allows you to view your Laravel log files in a simple UI. Inst

Ryan Chandler 9 Sep 17, 2022
This package allows you to easily work with NanoID in your Laravel models.

Laravel Model UUIDs Introduction Huge thanks to Micheal Dyrynda, whose work inspired me to create this package based on laravel-model-nanoid but uses

Parables Boltnoel 3 Jul 27, 2022
Validate your input data in a simple way, an easy way and right way. no framework required. For simple or large. project.

wepesi_validation this module will help to do your own input validation from http request POST or GET. INTEGRATION The integration is the simple thing

Boss 4 Dec 17, 2022
A package to validate email domains in a user registration form

This package allows to define a subset of allowed email domains and validate any user registration form with a custom rule.

H-FARM 56 Jul 19, 2022
A package to validate email domains in a user registration form

Laravel Email Domain Rule This package allows to define a subset of allowed email domains and validate any user registration form with a custom rule.

H-FARM Innovation 56 Jul 19, 2022
Package for Laravel that gives artisan commands to setup and edit environment files.

Setup and work with .env files in Laravel from the command line NOTE: This doesn't work with Laravel 5 since .env files were changed. This is for Lara

Matt Brunt 6 Dec 17, 2022
Laravel File Generators with config and publishable stubs

Laravel File Generators Custom Laravel File Generators with a config file and publishable stubs. You can publish the stubs. You can add your own stubs

Ben-Piet O'Callaghan 116 Oct 29, 2022
This Laravel Nova package allows you to manage media and media fields

Nova Media Hub This Laravel Nova package allows you to manage media and media fields. Requirements php: >=8.0 laravel/nova: ^4.0 Features Media Hub UI

outl1ne 25 Dec 22, 2022
Boilerplate code for protecting a form with proof of work. Uses javascript in the browser to generate the hashcash and PHP on the server to generate the puzzle and validate the proof of work.

Boilerplate code for protecting a form with proof of work. Uses javascript in the browser to generate the hashcash and PHP on the server to generate the puzzle and validate the proof of work.

Jameson Lopp 28 Dec 19, 2022