CodeIgniter 4 Array in Config with .env file

The .env file can use dot syntax to represent associative arrays but the documentation is poor, here is how I did it.

Create a new class in the Config directory e.g. Salesforce.php

 '',
		'account2' => ''
	];
	public $campaigns = [
		'campaign1' => '',
		'campaign2' => ''
	];
}

Add lines to the .env file

salesforce.accounts.account1 = 'config('Salesforce');';
salesforce.accounts.account2 = '00123451HKB';
salesforce.campaigns.campaign1 = '1234000000dBAEvA';
salesforce.campaigns.campaign2 = '1234000000dBAEvB';

Finally to access within your controller

$salesforce = config('Salesforce');
echo $salesforce['account1']; // displays 00123451HKB
echo $salesforce['campaign2']; // displays 1234000000dBAEvB

Advantages: You commit can commit the files in the Config folder to version control without them storing sensitive information while the sensitive data stays in the .env file and is unique to a particular environment.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.