Laravel define global constants Config php file

Panjeh
4 min readFeb 16, 2019

--

If you look at the main Laravel directory you can find these subdirectories:

Laravel 5.7 sub-directories

If you open the config sub-directory you can see it includes of some files:

config directory

Before you continue with the rest of this tutorial, I would like to introduce two packages for Laravel that I have recently developed: Laravel Pay Pocket, a modern multi-wallet package, and Laravel Failed Jobs, a UI for the Laravel Failed Jobs Table. I hope they may be of help to you.

https://github.com/HPWebdeveloper/laravel-pay-pocket
https://github.com/HPWebdeveloper/laravel-failed-jobs

If you open each config file you see such pattern :

<?phpreturn ['A' => valueA,'B' => valueB,];

It means if you want to define global constants you should make your own config file in the config sub-directory similar to the above pattern.

For an example the content of config/app.php file is:

<?phpreturn ['name' => env('APP_NAME', 'Laravel'),'env' => env('APP_ENV', 'production'),];

Whenever you need to access “name” or “env” constants you have two options:

Option A:

Using helper function (reference link)

config('app.name');
config('app.env');

The configuration values may be accessed using “dot” syntax, which includes the name of the file and option you wish to access. Since these constants are stored in the app.php file you should use “app.name” and “app.env ”to retrieve them.

OptionB:

Using Laravel Config:: facade

$name= Config::get(‘app.name’);

And don’t forget to include at the top of the controller this:

use Illuminate\Support\Facades\Config;

Or you may prefer the below style:

\Config::get(‘app.name’);

Note 1:

After making your own config file in config sub-directory don’t forget to do this:

php artisan config:cache

Note 2:

If you want to set configuration values at runtime such as value= ‘test’ for the constant bar in the file config/foo.php, do this:

Config::set('foo.bar', 'test');

or by passing an array of key / value pairs to the helper function:

config(['foo.bar' => 'test']);

Note 3:

Imagine you prepared a config file like foo.php with this content:

<?phpreturn ['bar' => [           'A' => valueA,           'B' => valueB,
],
];

In order to access the value of “A” do this:

Config::get('foo.bar.A');

and for “B”:

Config::get('foo.bar.B');

Thank you for reading! If you enjoyed this article:

Clap it ! Share it! Follow Me in Medium!

Also I’d like to hear your opinion on this article. If you have any doubt, question or suggestion please leave a comment below.

Have a very wonderful day!

Previous Stories You will Love:

--

--

Panjeh
Panjeh

Written by Panjeh

Posting about Python and Laravel

Responses (3)