How to Validate Your Laravel App's Config

Published on : July 27,2022
How to Validate Your Laravel App's Config

Hi Developer,

As your Laravel projects change and grow, it's likely that you'll add new config fields and onboard new team members to work alongside you. Especially for junior developers, setting up config and environment variables on your local development machine for the first time for each project can sometimes (but not always) be quite confusing.

You can sometimes find yourself scratching your head thinking "have I put the right API key here?", or "is this the right URL for this environment variable?", and "what are the different values that this config field can be?".

Of course, these types of issues can be avoided with well written and up-to-date documentation. But, wouldn't it be better if these questions could be answered, and enforced, programmatically before running your app rather than by eye or waiting until your code fails during runtime?


What is Laravel Config Validator?

Laravel Config Validator is a package that I built with the aim of trying to solve these issues by providing the ability for developers to define rules that can be used to validate config fields. It allows you to validate your config fields using an Artisan command so that you and other developers can be sure that they have the correct config set up.

The main benefit of using this package is that it encourages code-as-documentation, because you can update your config validation rules each time your config changes rather than updating a boring markdown file with your project's documentation that's likely hidden away and never looked at.

It also allows you to write complex rules relatively easily. For example, let's say that you had a config field that stored your Mailgun API keys. You could write a simple rule to make sure that the key is present and is a string. But, you could take it one step further and write a rule that makes a HTTP request to the API to confirm that the keys are actually valid and can be used to make the requests in your application.

To get a better idea of how this might look in your codebase, here's a basic example of how we could validate that a services.mailchimp.api_key field could be validated:

use AshAllenDesign\ConfigValidator\Services\Rule;
use App\Rules\ValidMailchimpKey;
return [
        ->rules(['required', 'string', new ValidMailchimpKey()]),

After defining a rule like above, we could then run the package's provided command (php artisan config:validate). If the services.mailchimp.api_key field is valid, the validation will pass. Otherwise, the command will return a list of the errors so that we can spot the incorrect config value, similar to in this example screenshot below:


The best part about the package (in my opinion) is that you don't need to learn any new syntax! Under the hood, the package uses the Validator provided by Laravel. So, you can use the same rules that you would typically use in your request validation.

Now, let's take a look at how you can install the package and start using it in your own projects.


Installing the Package

To get started with using the package, you'll need to make sure that your Laravel project is using at least Laravel 8.0 and PHP 8.0.

You can install the package via Composer using the following command:

composer require ashallendesign/laravel-config-validator

The package ships with some handy rulesets that you can use to validate some of the default Laravel config fields. These are completely optional, but they can provide a good starting point for validating your app's config. If you want to use the default 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's root. These rules are just to get you started, so there will likely be some rules that aren't needed for your project. So, once you've published them, feel free to delete them or edit them as much as you'd like.


Defining Config Validation Rulesets

Now that we have the package installed, we can start creating our own rulesets.

Creating new rulesets is really simple using the package's provided command. For example, if we wanted to create a ruleset for validating the config in the config/app.php file, we could run 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.

It's important to remember that your config validation files' names need to match the config file that you want to validate. For example, if you want to validate your config/mail.php file, your validation file would need to be stored as config-validation/mail.php.


Adding Rules to a Ruleset

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

Under the hood, the package uses the built-in Validator class that ships with Laravel and makes use of all the existing validation rules available in Laravel, so working with it should seem pretty familiar.

Let's take a basic example and create a new validation rule for the driver field in the app/mail.php file. We'll define a rule that says the field must be one of the following: smtp, sendmail, mailgun, ses, or postmark. To do this, we could write the following rule:

use AshAllenDesign\ConfigValidator\Services\Rule;
return [
    // ...
    // ...

As you can see, it's really simply to define a rule!


Custom Validation Error Messages

There may be times when you want to override the default error message for a specific validation rule. This is simple to do using the messages method on the Rule object when defining your rulesets.

For example, if we wanted to override the error message for our mail.driver config validation rule that we've created, we could do it like so:

use AshAllenDesign\ConfigValidator\Services\Rule;
return [
    // ...
        ->messages(['in' => 'Our custom error message here']),
    // ...


Only Running in Specific App Environments

It's possible that you might want to create rules that should only ever be run in specific environments. For example, you might want to create a relaxed set of validation rules for your local development environment and have a stricter set of rules for production.

To specify the environment that a rule can be run in, you can use the environments method available on the Rule object. If no environment is defined, the rule will be run in all environments by default.

For example, let's imagine that when we're working on our project locally, we don't really care which mail driver we're using. But, when in production, we want to make sure that we are only using mailgun. So, we could create a relaxed rule to run locally and a stricter rule to run in production like so:

use AshAllenDesign\ConfigValidator\Services\Rule;
return [


Running the Config Validation

Now that we've learned how to define our own config validation rulesets, let's take a look at how to actually run the validation.


Using the Command

The most common (and easiest) way that you can run your config validation is using the Artisan command that ships with the package.

You can use it by running the following command:

php artisan config:validate

However, you might not always want to validate all the config values in your application. So, the command allows you to specify the exact config files that you want to validate. To do this, you can use the --files option.

For example, if we only wanted to validate the config/auth.php file, we could run the following command:

php artisan config:validate --files=auth

Likewise, if wanted to explicitly define more than one file to validate at once, we could pass multiple names to the --files option separated by commas. For example, to validate the config/auth.php and config/services.php files, we could run the following command:

php artisan config:validate --files=auth,services


Running the Validation Manually

There may be times when you'd prefer to run the validation command manually in your code, rather than using the provided command. To do this, you can simply call the run method on the AshAllenDesign\ConfigValidator\Services\ConfigValidator class like so:

use AshAllenDesign\ConfigValidator\Services\ConfigValidator;
(new ConfigValidator())->run();

By default, the run method will return true if all the validation checks pass. If any of the checks fail, an AshAllenDesign\ConfigValidator\Exceptions\InvalidConfigValueException will be thrown.

Similar to how we can define the specific validation rulesets that should be run using the command, we can also do the same with the ConfigValidator object. To do this, we can pass an array of config file names to the run method.

For example, if we wanted to only run the validation for the config/auth.php file, we could use the following code:

use AshAllenDesign\ConfigValidator\Services\ConfigValidator;
(new ConfigValidator())->run(['auth']);


Running in a Service Provider

A good example of where you might want to manually run your config validation could be in a service provider. This is an ideal place to run the config validation rules in your local environment when developing to make sure that you have all the valid values. This is particularly useful if you are jumping between Git branches often that include different fields with different required config fields.

Here's how we could automatically run the config validation on each request in our local environment, and ignore it when running in production or testing:

namespace App\Providers;
use AshAllenDesign\ConfigValidator\Services\ConfigValidator;
use Illuminate\Support\Facades\App;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
    public function boot()
        if (App::environment() === 'local') {
            (new ConfigValidator())->run();


Throwing and Preventing Exceptions

As we mentioned above, by default, the ConfigValidator class will throw an AshAllenDesign\ConfigValidator\Exceptions\InvalidConfigValueException exception if the validation fails. The exception will contain the error message of the first config value that failed the validation.

However, there may be times when you don't want to throw an exception on the first failure and would rather run all the rules at once. To do this, 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. If we disable exceptions from being thrown, the run method will return false if any of the validation checks fail.

By preventing any exceptions from being thrown, we can then get the failed validation errors using the errors method, which will return them as an array.

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

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

This is actually how the package's command runs the validator so that it can display all the failures in the output at once.

Hope it can help you…

Categories : Laravel PHP

Tags : PHP Laravel Laravel 9

Praful Sangani
Praful Sangani
I'm a passionate full-stack developer with expertise in PHP, Laravel, Angular, React Js, Vue, Node, Javascript, JQuery, Codeigniter, and Bootstrap. I enjoy sharing my knowledge by writing tutorials and providing tips to others in the industry. I prioritize consistency and hard work, and I always aim to improve my skills to keep up with the latest advancements. As the owner of Open Code Solution, I'm committed to providing high-quality services to help clients achieve their business goals.


order fenofibrate pill buy tricor for sale order generic tricor 200mg

order cialis 20mg pills order viagra 100mg sale viagra 25mg

ketotifen 1 mg pill buy imipramine pills order tofranil

purchase minoxidil order generic cialis 20mg buy cheap ed pills

acarbose online buy order acarbose 50mg without prescription fulvicin price

oral aspirin buy imiquad sale purchase imiquad online cheap

cheap meloset 3 mg cheap cerazette 0.075mg danocrine 100mg us

dipyridamole order online purchase pravastatin pravachol 10mg without prescription

duphaston 10 mg usa duphaston 10mg generic jardiance price

brand fludrocortisone 100mcg rabeprazole online buy order imodium 2mg generic

order monograph 600 mg sale buy generic monograph buy generic cilostazol

buy prasugrel pills detrol for sale online tolterodine 1mg pill

mestinon uk buy feldene 20 mg without prescription buy rizatriptan paypal

order ferrous sulfate 100mg for sale ascorbic acid 500mg brand buy betapace 40 mg online

buy generic enalapril online duphalac bottless cost lactulose

buy cheap xalatan purchase capecitabine order generic rivastigmine 6mg

betahistine where to buy probalan us buy benemid 500mg online

brand premarin 0.625mg buy premarin cheap sildenafil 20mg

order omeprazole 10mg pills metoprolol medication metoprolol 100mg brand

tadalafil 10mg cost viagra for women sildenafil tablet

buy micardis 80mg without prescription telmisartan drug buy molnupiravir generic

order modafinil without prescription order promethazine online buy generic prednisone

cefdinir price metformin 500mg over the counter cheap prevacid 30mg

absorica online buy azithromycin 250mg cost order azithromycin without prescription

order azipro 500mg online order generic omnacortil buy neurontin 600mg pills

order atorvastatin 40mg online cheap amlodipine uk buy amlodipine 10mg without prescription

gambling games furosemide 40mg usa order generic lasix 40mg

brand protonix 20mg generic protonix order generic phenazopyridine 200 mg

casino online ventolin inhalator over the counter ventolin us

online casino games real money play great poker online ivermectin 3mg tablet

buy amantadine 100 mg without prescription generic aczone 100mg buy dapsone 100mg for sale

online blackjack best buy clavulanate paypal cheap levothyroxine pill

order clomiphene 50mg imdur 20mg tablet buy azathioprine 25mg generic

medrol tablets how to get triamcinolone without a prescription triamcinolone cost

vardenafil 20mg for sale tizanidine for sale online cost zanaflex

coversyl pills buy generic aceon over the counter allegra price

dilantin generic cyclobenzaprine online buy buy generic ditropan

ozobax cost lioresal order toradol 10mg canada

claritin 10mg canada ramipril buy online buy dapoxetine for sale

buy ozobax without a prescription baclofen 25mg pill toradol oral

fosamax uk buy macrodantin 100 mg generic buy furadantin 100 mg without prescription

oral glimepiride 4mg cytotec 200mcg cheap etoricoxib 120mg for sale

buy generic propranolol for sale propranolol over the counter oral plavix 150mg

brand nortriptyline 25 mg buy pamelor online cheap anacin 500 mg pills

warfarin sale brand reglan order maxolon pill

xenical 60mg usa buy diltiazem 180mg pills buy diltiazem tablets

order famotidine 40mg pill purchase famotidine sale where to buy prograf without a prescription

brand astelin 10ml azelastine 10 ml price avapro online order

order esomeprazole 20mg topamax 200mg uk topamax brand

sumatriptan 25mg over the counter order imitrex 25mg online dutasteride medication

purchase zyloprim generic purchase temovate online cheap rosuvastatin 20mg uk

order generic ranitidine celecoxib 200mg pill buy celebrex 200mg pills

buspar pills oral ezetimibe 10mg order cordarone 200mg pills

flomax drug order simvastatin 20mg zocor over the counter

buy motilium generic brand coreg 25mg purchase tetracycline generic

order aldactone 100mg generic purchase finasteride generic order proscar 1mg online

assignments for sale assignment website write me a paper

cost diflucan 100mg order forcan generic cipro 500mg without prescription

aurogra 100mg generic estrace brand estrace 2mg price

buy flagyl 200mg generic bactrim 480mg price keflex 500mg tablet

buy lamictal 50mg pills purchase vermox pills generic mebendazole

order cleocin generic buy erythromycin generic purchase sildenafil online cheap

buy tretinoin sale order tretinoin gel online avanafil medication

order nolvadex 10mg online how to buy budesonide symbicort cheap

tadacip 10mg us voltaren price indocin canada

buy cefuroxime 250mg online cheap buy cefuroxime 250mg pill methocarbamol 500mg pill

order desyrel 100mg online suhagra 50mg us purchase clindac a for sale

lamisil without prescription gambling online online slots real money

buy aspirin 75 mg for sale play slots online free spins no deposit casino

help writing papers linking words in essay writing cefixime 200mg without prescription

affordable thesis writing online real gambling real money real money casino app

buy trimox 500mg online order generic trimox oral biaxin 250mg

calcitriol 0.25mg price where to buy tricor without a prescription order fenofibrate 200mg generic

clonidine 0.1 mg price buy tiotropium bromide buy spiriva 9mcg online

expensive acne medication popular acne prescriptions order oxcarbazepine online cheap

minocin online order order terazosin 5mg online cheap requip order online

order alfuzosin 10 mg heartburn medicine without calcium nausea medication for chemo patients

sleeping pills over the counter fda approved drug hair loss best diet pills from mexico

letrozole 2.5 mg generic buy albendazole 400 mg generic order aripiprazole 30mg without prescription

herbal supplements for quitting smoking nhs stop smoking advice buy medication online australia

order provera 10mg oral biltricide 600mg buy hydrochlorothiazide 25 mg generic

genital herpes relief over counter a1c reduction by drug class diabetic pills names

buy periactin 4mg for sale cyproheptadine 4 mg over the counter buy ketoconazole pills for sale

can vitamins cause yeast infection how to not spread hsv2 abruptly stopping blood pressure medication

buy duloxetine paypal order provigil 200mg online cheap order provigil 100mg online cheap

instant stomach relief for ulcer side effects of vasodilators bacterial infection in bladder women

purchase promethazine online cheap stromectol 6mg cost ivermectin 3mg over the counter

superdrug order contraceptive pill men last longer pills how to last longer in bed as a man

buy generic prednisone 40mg buy prednisone online cheap amoxicillin 500mg without prescription

heartburn meds over the counter best med for gas pain medication for flatulence australia

order azithromycin gabapentin 800mg cost neurontin 100mg price

urso buy online actigall order buy cetirizine 5mg generic

order strattera 25mg without prescription brand strattera order zoloft generic

lasix over the counter buy acticlate online cheap generic ventolin 4mg

buy lexapro tablets order escitalopram 10mg naltrexone online

augmentin 375mg for sale buy clomid generic clomiphene 50mg drug

ipratropium 100mcg usa order decadron 0,5 mg online purchase zyvox for sale

starlix online candesartan 16mg price order candesartan 16mg generic

starlix 120 mg oral buy starlix 120mg generic buy candesartan generic

where to buy vardenafil without a prescription buy plaquenil 200mg generic plaquenil without prescription

carbamazepine sale ciplox order online buy lincocin online

how to buy cenforce order glucophage online glucophage 500mg ca

cefadroxil for sale online order epivir sale lamivudine over the counter

buy atorvastatin 10mg sale where can i buy lisinopril zestril 10mg canada

cabergoline 0.5mg price cost claritin buy generic dapoxetine 60mg

methylprednisolone 8 mg online methylprednisolone 4mg for sale clarinex 5mg pill

order misoprostol 200mcg online cheap diltiazem order online order diltiazem 180mg generic

nootropil 800mg oral order nootropil 800 mg generic clomipramine 25mg pills

buy generic acyclovir 800mg allopurinol 100mg without prescription rosuvastatin 10mg usa

order sporanox pill tinidazole 300mg pill buy tindamax pills for sale

order zetia 10mg pills tetracycline over the counter order tetracycline 250mg for sale

olanzapine oral valsartan 160mg sale where can i buy valsartan

order flexeril without prescription buy lioresal medication where can i buy toradol

gloperba over the counter methotrexate 10mg pills purchase methotrexate without prescription

prescription medication for adult acne prednisone 40mg us acne medication by prescription

allergy pills non drowsy phenergan oral alternative allergy treatment options

prescription heartburn pills drugs for nausea from chemo

prednisone 20mg without prescription order prednisone 40mg online cheap

best medication for heartburn order epivir sale

dr prescribed acne medication betamethasone uk acne medication by prescription

best prescription drug for gerd buy generic metformin

accutane online buy buy isotretinoin 20mg pills buy accutane generic

buy amoxicillin 1000mg without prescription amoxicillin pills cheap amoxicillin generic

oral zithromax order zithromax 500mg online cheap zithromax medication

generic gabapentin 100mg neurontin 800mg usa

buy azithromycin generic azipro drug cheap azithromycin 250mg

furosemide uk how to buy lasix

prednisolone pills prednisolone 10mg oral purchase prednisolone generic

doxycycline pill generic doxycycline

albuterol price buy generic ventolin over the counter albuterol inhalator for sale online

buy clavulanate pills for sale buy augmentin pill

order levothroid without prescription order synthroid 100mcg online synthroid canada

levitra order buy levitra sale

serophene over the counter buy clomid clomiphene ca

cheap tizanidine 2mg where to buy tizanidine without a prescription order tizanidine 2mg without prescription

purchase semaglutide generic rybelsus 14mg price buy rybelsus for sale

prednisone 20mg cheap deltasone drug buy prednisone 40mg generic

isotretinoin 40mg tablet order generic accutane 40mg order isotretinoin 20mg pill

buy cheap generic semaglutide buy semaglutide 14 mg without prescription oral semaglutide 14 mg

albuterol over the counter order ventolin 2mg pill ventolin 2mg pills

amoxicillin medication amoxicillin 1000mg without prescription buy amoxil cheap

buy cheap generic augmentin order generic augmentin 1000mg amoxiclav buy online

zithromax 500mg us brand zithromax 250mg azithromycin pill

buy synthroid pills for sale synthroid 150mcg usa order levothyroxine generic

purchase omnacortil generic cost prednisolone 10mg buy omnacortil medication

buy vardenafil generic buy vardenafil for sale cheap levitra

best casino gambling casino online online slots

purchase hydroxychloroquine generic buy plaquenil 200mg online order plaquenil 400mg pills

order lyrica 75mg pill buy pregabalin online cheap pregabalin generic

us pharmacy cialis purchase cialis for sale cialis uk

order triamcinolone 4mg sale triamcinolone cheap triamcinolone 10mg cost

oral cenforce 50mg buy cenforce 100mg sale buy generic cenforce for sale

buy clarinex online cost clarinex 5mg buy clarinex online cheap

aralen 250mg uk where can i buy aralen order chloroquine 250mg online cheap

order loratadine 10mg pills cheap claritin 10mg claritin sale

order generic xenical 60mg buy diltiazem cheap how to get diltiazem without a prescription

atorvastatin 40mg price buy generic atorvastatin 10mg order lipitor 40mg generic

brand amlodipine 5mg order amlodipine 5mg sale norvasc without prescription

buy generic zovirax online order allopurinol 300mg pills where to buy allopurinol without a prescription

buy lisinopril 5mg generic order lisinopril generic buy zestril no prescription

buy crestor pill buy rosuvastatin online cheap buy zetia 10mg generic

purchase prilosec online cheap omeprazole 20mg without prescription prilosec us

buy generic domperidone for sale sumycin over the counter buy sumycin online

metoprolol medication buy lopressor 50mg without prescription order lopressor 100mg without prescription

cyclobenzaprine oral order flexeril generic lioresal without prescription

Leave a comment

We'll never share your email with anyone else. Required fields are marked *

Related Articles

Access specifier in php
Praful Sangani By Praful Sangani - July 20,2022