Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom .env variable on Codeigniter 4

Normally if i want to change the database hostname in CI4 project i will change it in .env file and change the

database.default.hostname = localhost

but now i need to use MYSQL_HOST in env to change the hostname like so

MYSQL_HOST = localhost

can i do that in CI4? it will give error if i change the Database.php file to

public $default = [
    'DSN'      => '',
    'hostname' => getenv('MYSQL_HOST'),
    'username' => '',
    'password' => '',
    'database' => '',
    'DBDriver' => 'MySQLi',
    'DBPrefix' => '',
    'pConnect' => false,
    'DBDebug'  => (ENVIRONMENT !== 'production'),
    'charset'  => 'utf8',
    'DBCollat' => 'utf8_general_ci',
    'swapPre'  => '',
    'encrypt'  => false,
    'compress' => false,
    'strictOn' => false,
    'failover' => [],
    'port'     => 3306,
];
like image 612
Deandra Abiantoro Avatar asked Oct 19 '25 05:10

Deandra Abiantoro


1 Answers

I found the answer, lets say you have this in you .env file

MYSQL_HOST = localhost
MYSQL_USERNAME = root
MYSQL_PASSWORD = root

so if you want to change hostname of CI4 database you can add

$this->default['hostname'] = getenv('MYSQL_HOST');

inside __construct() in app/config/Database.php

so it will be look like this

public function __construct()
{
    parent::__construct();

    // Ensure that we always set the database group to 'tests' if
    // we are currently running an automated test suite, so that
    // we don't overwrite live data on accident.
    if (ENVIRONMENT === 'testing') {
        $this->defaultGroup = 'tests';
    }
    $this->default['hostname'] = getenv('MYSQL_HOST');
    $this->default['username'] = getenv('MYSQL_USERNAME');
    $this->default['password'] = getenv('MYSQL_PASSWORD');
}

well this is only if you want to custom your .env and dont want to use the default CI4 database.default.hostname

like image 83
Deandra Abiantoro Avatar answered Oct 22 '25 04:10

Deandra Abiantoro