Welcome Guest, Not a member yet? Register   Sign In
Codeigniter 4 Load settings from database

I would like to load few settings that is previously stored in Database (e.g. site language, site name etc.) and those settings will be used everywhere in the application. Previously in Codeigniter 3 I've done this by adding below code in application/config/config.php file.

require_once(BASEPATH . 'database/DB.php');
$db =& DB();
$config['general_settings'] = $db->get('general_settings')->row();
$config['languages'] = $db->get('languages')->result();

But I'm bit confused about to Codeigniter 4 where or in which file I should put this code to get expected result. Any suggestion?

In CI 4 that would be app/Config/app.php
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )

You can create your own configuration file and this file may contain any properties and methods as you want. You can use it in your application wherever - just load it with namespase as usual config class.

(11-03-2020, 08:50 PM)InsiteFX Wrote: In CI 4 that would be app/Config/app.php
Yes, I understand It would be there. Can you give a code snippet, so I can better understand how i can put it there. Thank you.

After several attempts I got the way to overcome this issue.

First need to create a Custom Config file in App/Config directory. Let’s say my Custom Config name is MyConfig.php
<?php namespace Config;
    use CodeIgniter\Config\BaseConfig;
    use Config\Database;
    class MyConfig extends BaseConfig
        public function __construct ()
            $db = Database::connect();
                $get_general_settings = $db->query('SELECT * FROM general_settings');
                $this->general_settings = $get_general_settings->getRow();
                $get_languages = $db->query('SELECT * FROM languages');
                $this->languages = $get_languages->getResult();

Now It can be used in any Controller or anywhere. Example: $myconfig = config('MyConfig');

@Hemil you may want to check out Tatter\Settings which manages exactly this in a separate service: https://github.com/tattersoftware/codeigniter4-settings

Your implementation might look something like this...

1. Install with Composer: > composer require tatter/settings
2. Update the database: > php spark migrate -all
3. Add settings: > php spark settings:add timezone user America/New_York

Using it:
PHP Code:
// Load the service
$settings service('settings');

// Access a setting
echo $settings->timezone// "America/New_York"

// Change a setting
$settings->timezone 'America/Chicago'

Theme © iAndrew 2016 - Forum software by © MyBB