ホーム > Laravel > Introduction to the Relationship Between Laravel's Config and Env for Beginners
Laravel

Introduction to the Relationship Between Laravel's Config and Env for Beginners

Thank you for your continued support.
This article contains advertisements that help fund our operations.

⇨ Click here for the table of contents for Laravel articles

Why Write This

When trying to install a new package,

You need to edit config/***.php

But in reality, the file you need to edit is

.env file

I hope you can understand this.

What is config/***php

Files in the config directory allow you to write

  • Constants accessible from anywhere in the application.

There, you can

  1. Change application settings
  2. Set access keys for using packages

What is .env?

.env is a file that should not be included in git.

As the name suggests, it is a file to write

  1. Information you want to change constants based on the environment
  2. Information that should not be included in git (such as secret keys)

Relationship between config and .env

Among the constants you want to set in config,

  1. Information you want to change constants based on the environment
  2. Information that should not be included in git (such as secret keys)

should be written in .env.

Implementation

When you install Laravel, there are various configuration files,

Let's take a look at config/mail.php as an example.

<?php

return [
    'driver' => env('MAIL_DRIVER', 'smtp'),

You may find such a description.

This means that the configuration reads the

MAIL_DRIVER=

item in the .env file. Also, the second argument

smtp

is the initial value when the setting is not written in .env.

In other words, by changing .env according to each environment, the constants in the config are changed.

Reflecting Changes in config Constants

Config constants may not be reflected just by changing the file because they are cached.

Therefore, run the command

php artisan config:cache

Or,

php artisan config:clear

to reflect the changes.

How to Use Config Constants

For example, in controllers,

config('mail.smtp') //mail is the file name.

to call the constants.

Conclusion

  • Since the files installed with packages have config('mail.smtp') written in them, you need to prepare certain config constants for them to work.

This is the gist of it.

Summary

That's all. I wrote this because I think config and env can be quite confusing at first.

I hope this can be useful to someone.

For feedback or complaints, please contact me via Twitter DM.

That's all!

Popular Articles

Deploying a PHP7.4 + Laravel6 Project to AWS EC2

Implementing Breadcrumbs in Laravel with laravel-breadcrumbs

Please Provide Feedback
We would appreciate your feedback on this article. Feel free to leave a comment on any relevant YouTube video or reach out through the contact form. Thank you!