Creating Your Own Configuration in Laravel

Published on by

Creating Your Own Configuration in Laravel image

Laravel configuration allows you to define per-environment configuration with the excellent vlucas/phpdotenv package.

If you are new to Laravel, you might not yet know how you can create your configuration files in your projects and a few other helpful things that will help you master configuration. As always, the official documentation provides great information, and there are a few things we’ll cover here that I think will help people new to the Laravel framework.

How Does Configuration Work?

At a high level, configuration files are located in the config/ folder of a Laravel project. The framework ships with various configuration files that make it easy for you to do things like pick which database driver you want to use and define external services.

For example, here is a partial view of the config/services.php config file:

return [
// ...
'mailgun' => [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
],
 
// ...

Note the env() calls that you can use to change values per-environment with the .env file or on the host system directly.

When you define an environment configuration on your machine, it takes precedence over the .env file.

The env() helper also allows you to specify a default value when the environment variable is missing on the system or the .env file. For example, the default connection in config/database.php is mysql when the DB_CONNECTION environment variable is not defined:

<?php
 
return [
'default' => env('DB_CONNECTION', 'mysql'),
 
// ...
];

All environment values from the phpdotenv package come back as strings, but the env() helper in Laravel does extra work with environment variables. For example, the Laravel helper converts “false” the string to Boolean false, the keyword “empty” to an empty string, and “null” to a null value. You can check out the source of the Illuminate support helpers.php file for more details.

Accessing the Configuration Service

The most common ways to access configuration in Laravel is through the Configuration service or the config() helper.

Here’s how you use the config service:

$ php artisan tinker
 
>>> app('config')->get('services');
=> [
"mailgun" => [
"domain" => null,
"secret" => null,
],
"ses" => [
"key" => null,
"secret" => null,
"region" => "us-east-1",
],
"sparkpost" => [
"secret" => null,
],
"stripe" => [
"model" => "App\User",
"key" => null,
"secret" => null,
],
]

The config() helper provides convenience, and you can still access the configuration repository service if you don’t pass any arguments:

$ php artisan tinker
 
>>> config()
=> Illuminate\Config\Repository {#37}
 
>>> config()->get('services')
...
>>> config('services')

Working with Configuration

Configuration is defined in PHP arrays, and you can access those array values with a dot notation. The first part of the configuration key matches the name of the file. For example, the following is the config/services.php file:

$ php artisan tinker
 
>>> config('services.mailgun');
=> [
"domain" => "mg.example.com",
"secret" => "secret",
]
>>> config('services.mailgun.domain');
=> mg.example.com

Just like the env() helper, the config helper allows you to specify a default value if the configuration key isn’t defined:

$ php artisan tinker
 
>>> config('my.invalid.key', 'mg.example.com');
=> mg.example.com

You can also change/set configuration at runtime by passing the configuration helper an array:

>>> config(['example' => 'Hello World']);
=> null
>>> config('example');
=> "Hello World"
 
>>> config([
... 'view.paths' =>
... array_merge(config('view.paths'), ['my/other/path/'])
... ]);

Creating Your Own Configuration

You can create your own configuration files by adding them to the config/ folder:

$ touch config/api.php

You would then access the configuration values by prefixing “api”:

>>> config('api.base_url');

This is just an example, for services like APIs just use the config/services.php file by adding new keys, for example, let’s say you are adding auth0 to services.php:

<?php
 
return [
'auth0' => [
'secret' => env('AUTH0_CLIENT_SECRET')
],
];

Optimizing Configuration

When you deploy your application to production, you should optimize your configuration by running the following command:

$ php artisan config:cache

There are a couple of important points to make about this command:

  1. This command is not intended for development environments
  2. Make sure you are not calling env() outside of configuration files

When you cache configuration, things like tests will use these cached values. For example, your database credentials will be cached and running tests with database interactions will drop your database tables.

When you cache your configuration, make sure your code is not calling the env() helper. You should be using config() wherever you need to access configuration. The correct way to provide configuration to your application is using configuration files in tandem with environment variables with sensible default values.

You can clear the configuration cache with the following artisan command:

$ php artisan config:clear

Learn More

I hope this has been helpful to those just starting to learn about Laravel. Be sure to read the official configuration documentation. If you are interested in writing your packages, check out the package configuration resources documentation.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Forge
Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
Larafast: Laravel SaaS Starter Kit logo

Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes. Available with VILT and TALL stacks.

Larafast: Laravel SaaS Starter Kit
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector

The latest

View all →
Sort Elements with the Alpine.js Sort Plugin image

Sort Elements with the Alpine.js Sort Plugin

Read article
Microsoft Clarity Integration for Laravel image

Microsoft Clarity Integration for Laravel

Read article
Apply Dynamic Filters to Eloquent Models with the Filterable Package image

Apply Dynamic Filters to Eloquent Models with the Filterable Package

Read article
Property Hooks Get Closer to Becoming a Reality in PHP 8.4 image

Property Hooks Get Closer to Becoming a Reality in PHP 8.4

Read article
Asserting Exceptions in Laravel Tests image

Asserting Exceptions in Laravel Tests

Read article
Reversible Form Prompts and a New Exceptions Facade in Laravel 11.4 image

Reversible Form Prompts and a New Exceptions Facade in Laravel 11.4

Read article