Anonymous
Anonymous

Reputation: 13

PHP - Access data for .env laravel

I am starting the program with Laravel and I have in my ".env" file my access data to the server:

USER_SERVER=user
PASSWORD_SERVER=123456789

I have my role in my controller:

 public function connectServer()
    {
        $connection=ssh2_connect(172.17.2.33, 22);
        ssh2_auth_password($connection, USER_SERVER, PASSWORD_SERVER);

$stream=ssh2_exec($connection, "df -h");
        $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
}

My role above has problems. What is the correct way to call the user and password of my ".env" file for my function?

Upvotes: 1

Views: 42

Answers (1)

lagbox
lagbox

Reputation: 50511

You should use the configuration system for these values. You can add to a current configuration file in the config folder or create your own that returns an associative array. We will use the env() helper to pull the values you set in the .env file:

<?php

return [
   ...
   'server' => [
       'user' => env('USER_SERVER', 'some default value if you would like'),
       'password' => env('PASSWORD_SERVER', ...),
    ],
    ...
];

If you added this key to the services.php file in the config folder you would then access this configuration value via the Config facade or the config() helper function:

// if we want a value from the services.php file
Config::get('services.server.user');
config('services.server.user');

// if you want all of them for that server array
$config = config('services.server');
echo $config['user'];

Using the configuration system this way allows you to use the "config caching" that Laravel provides, as you will not have any env() calls in your application, except for in the config files, which can be cached. [When configuration caching is in place it doesn't load the env]

"If you execute the config:cache command during your deployment process, you should be sure that you are only calling the env function from within your configuration files. Once the configuration has been cached, the .env file will not be loaded and all calls to the env function will return null." - Laravel 7.x Docs - Configuration - Configuration Caching

Laravel 7.x Docs - Configuration - Accessing Configuration Values config()

Laravel 7.x Docs - Configuraiton - Retrieving Environmental Configuration env()

Upvotes: 1

Related Questions