env-in-CodeIgniter icon indicating copy to clipboard operation
env-in-CodeIgniter copied to clipboard

Database cannot be autoload

Open iddemirjs opened this issue 4 years ago • 4 comments

When I added to database in to autoload file. Dot env is not working. How can I solve that?

iddemirjs avatar Nov 04 '21 20:11 iddemirjs

Seeing the exact same thing on CI3.

It looks like the database helper will be loaded before the .env files are processed which causes any env() calls in the database.php to fail.

anthony-n-brown avatar Nov 08 '21 18:11 anthony-n-brown

In system\core\Loader.php, they prioritize loading of the database before any other libraries:

		// Load libraries
		if (isset($autoload['libraries']) && count($autoload['libraries']) > 0)
		{
			// Load the database driver.
			if (in_array('database', $autoload['libraries']))
			{
				$this->database();
				$autoload['libraries'] = array_diff($autoload['libraries'], array('database'));
			}

			// Load all other libraries
			$this->library($autoload['libraries']);
		}

If you don't mind touching the Code Igniter code, you can workaround this issue by forcing env to be loaded before database like:

		// Load libraries
		if (isset($autoload['libraries']) && count($autoload['libraries']) > 0)
		{
			// Load the environment driver before the database code
			if (in_array('env', $autoload['libraries']))
			{
				$this->library('env');
				$autoload['libraries'] = array_diff($autoload['libraries'], array('env'));
			}
			// Load the database driver.
			if (in_array('database', $autoload['libraries']))
			{
				$this->database();
				$autoload['libraries'] = array_diff($autoload['libraries'], array('database'));
			}

			// Load all other libraries
			$this->library($autoload['libraries']);
		}

anthony-n-brown avatar Nov 08 '21 18:11 anthony-n-brown

Thanks for the guide :)

setsunafjustin00208 avatar Jul 22 '22 10:07 setsunafjustin00208

Thanks @anthony-n-brown it works :)

harshadduasane avatar Jan 25 '23 09:01 harshadduasane