Server level variables in Laravel
A few days ago we studied and saw how the environment and configuration variables work in Laravel. Today we will review a complementary topic, which is the flow between server-level variables and Laravel configuration variables.
Definition of server-level variables
If you have followed the steps in our post configuring a virtual host in Laravel with Apache, you probably already have a Laravel project installed and configured to work on a serverName
created for this purpose. Let's then make a modification to the site definition and create a server-level variable with Apache that defines the name of our application.
<VirtualHost *:80>
ServerName example.localhost.com
DocumentRoot "${SRVROOT}/htdocs/example/public/"
...
SetEnv APP_NAME ExampleApp
...
</virtualhost>
As you can see, the SetEnv
directive allows you to define variables in Apache that could be passed to CGI scripts or SSI pages.
Using variables defined at server-level
Now, let's go directly to the welcome.blade.php file in the resources/views folder and change the part of the content where the text Larevel is displayed so that it takes the application name from the configuration.
<div class="content">
<div class="title m-b-md">
<?= config('app.name') ?>
</div>
...
</div>
Once this is done, when accessing the main page of the application, we should see the modified framework initial screen.
What just happened is possible because any variable in the .env file can be overwritten by server-level variables such as the one defined in the Apache configuration. If you notice, in the .env configuration file there is a variable defined for the application name.
APP_NAME=Laravel
However, in the welcome view, we have not used the env
helper but the config
helper, so the variable is retrieved from the app.php file in the config directory.
'name' => env('APP_NAME', 'Laravel')
This variable ultimately queries the value of the variable in the .env file, however, the variable has been overwritten by the server configuration. This configuration scheme allows the application to take values according to the environment in which it is installed. On the other hand, it may be a bit cumbersome to define a variable both in the .env file and in the configuration files, however, when we review how Laravel caches these files so that the application can be optimized, we will understand a little more the importance of this scheme. For now, keep in mind that as a recommendation, the env
helper should only be used in configuration files. See you next time.