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
Battle Ready Laravel

The ultimate guide to auditing, testing, fixing and improving your Laravel applications so you can build better apps faster and with more confidence.

Visit Battle Ready Laravel
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
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
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
Cut PHP Code Review Time & Bugs into Half with CodeRabbit logo

Cut PHP Code Review Time & Bugs into Half with CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and custom review features while remaining free for open-source projects.

Cut PHP Code Review Time & Bugs into Half with CodeRabbit
Join the Mastering Laravel community logo

Join the Mastering Laravel community

Connect with experienced developers in a friendly, noise-free environment. Get insights, share ideas, and find support for your coding challenges. Join us today and elevate your Laravel skills!

Join the Mastering Laravel community
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
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

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
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant 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
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Confidently Extract Single Array Items with Laravel's Arr::sole() Method image

Confidently Extract Single Array Items with Laravel's Arr::sole() Method

Read article
Safely Retry API calls in Laravel image

Safely Retry API calls in Laravel

Read article
Laravel's AsHtmlString Cast for Elegant HTML Attribute Management image

Laravel's AsHtmlString Cast for Elegant HTML Attribute Management

Read article
NativePHP for Mobile v1 — Launching May 2 image

NativePHP for Mobile v1 — Launching May 2

Read article
Map Eloquent Attributes into an Object Using the Collection Cast in Laravel 12.10 image

Map Eloquent Attributes into an Object Using the Collection Cast in Laravel 12.10

Read article
Converting Array Values to Enum Instances with Laravel's mapInto Method image

Converting Array Values to Enum Instances with Laravel's mapInto Method

Read article