Laravel Dynamic Configuration Using MySQL

14 November 2018, in Web development
Share on Social Media: Share on facebook Share on twitter Share on google

Dynamic configuration is used to set the settings variable and values during request life cycle.Why is it required? Because most of the web sites required some of frequent changes on the configuration variables or settings variables.

And this approach is used to solve making a code change or new build of the application. So we just change the configuration value of the database and it gets affected across the website.

Let's start to create configuration table schema, We have two columns which is  config_key and config_value

config_key - Holds setting key
config_value - Holds setting value

And stored Values like this

Then, We are going to implement how to store values to the model using laravel

Create a Model 

We will use model to retrieve and store the configuration data.


namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Configuration extends Model
    protected $fillable = [];

    public function getSettings()
    	return Configuration::lists('config_value', 'config_key')->toArray();  

Then next we need to write a middleware to distribute the configuration values to across application. Here mentioned below middleware.

namespace App\Http\Middleware;

use Cache;
use Closure;
use App\Models\Configuration;

class Configuration

    public $settings;

    public function __construct(Configuration $settings)
        $this->settings = $settings;

     * Handle an incoming request.
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
    public function handle($request, Closure $next)
        $settings = Cache::get('settings');
        if(empty($settings) === true){
            $settings = $this->settings->getSettings();
            Cache::forever('settings', $settings);
        if(empty($settings) === false){

        return $next($request);

Then we need to enable this middleware by adding this to Http/Kernal.php

protected $routeMiddleware = [
    'dConfig' => \App\Http\Middleware\Configuration::class

All the routes must use this middleware. So that the dynamic config has been available across application

Example routes:

Route::group(['middleware' => ['dConfig']], function () {
	Route::get('/test', 'TestController@testAction');
Now configuration has been available across application and you can access it as follows.




Note: If you are caching the configuration then you must clear the cache after made the configuration changes