How to override config files of Laravel 4 package

If you want to be able to allow the users who use your package to publish and modify the package’s config files, you’ll need to add these into your Server Provider file, inside function register().

For example, my config files are structured like this:

- vendorname
  - packagename
    - src
      - config
        - image.php
        - config.php
        - menu.php

So within the PackagenameServiceProvider.php file, add these:

public function register()
{
  // other code omitted...

  // Get config loader
  $loader = $this->app['config']->getLoader();

  // Get environment name
  $env = $this->app['config']->getEnvironment();

  // Add package namespace with path set, override package if app config exists in the main app directory
 if (file_exists(app_path() .'/config/packages/vendorname/packagename')) {
 $loader->addNamespace('redminhrportal', app_path() .'/config/packages/vendorname/packagename');
 } else {
 $loader->addNamespace('packagename',__DIR__.'/../../config');
 }

  // Load package override config file
  $menu = $loader->load($env,'menu','packagename');
  $image = $loader->load($env,'image','packagename');
  $config = $loader->load($env,'config','packagename');

  // Override value
  $this->app['config']->set('packagename::menu',$menu);
  $this->app['config']->set('packagename::image',$image);
  $this->app['config']->set('packagename::config',$config);
}

To override the configuration files, users will have to publish the config file with the command below:

php artisan config:publish vendorname/packagename

Leave a Reply