PHPackages                             mohanad/laravel-config-switcher - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. mohanad/laravel-config-switcher

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

mohanad/laravel-config-switcher
===============================

A Laravel package for managing configuration and environment settings with snapshot/rollback functionality

00PHP

Since Sep 3Pushed 8mo agoCompare

[ Source](https://github.com/mohanadhilles/Config-Switcher)[ Packagist](https://packagist.org/packages/mohanad/laravel-config-switcher)[ RSS](/packages/mohanad-laravel-config-switcher/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Laravel Config Switcher
=======================

[](#laravel-config-switcher)

A powerful Laravel package for managing configuration and environment settings with snapshot/rollback functionality. This package provides a secure admin panel to manage your Laravel application's configuration files and environment variables with the ability to create snapshots and rollback to previous states.

Features
--------

[](#features)

- 🔧 **Environment Management**: Safely update `.env` file variables through a web interface
- 📁 **Config File Management**: Manage Laravel configuration files with validation
- 📸 **Snapshot System**: Create snapshots of your current configuration state
- 🔄 **Rollback Functionality**: Restore your configuration to any previous snapshot
- 🔒 **Security Features**: IP restrictions, user authentication, and validation rules
- 🎨 **Modern UI**: Beautiful, responsive admin panel built with Tailwind CSS
- ⚡ **Artisan Commands**: CLI commands for snapshot management
- 🧪 **Comprehensive Testing**: Full test coverage with PHPUnit

How It Works
------------

[](#how-it-works)

### 🏗️ **Architecture Overview**

[](#️-architecture-overview)

The Laravel Config Switcher package follows a clean, layered architecture that integrates seamlessly with Laravel:

```
User Request → Routes → Controller → Service → Database/File System
     ↑                                                      ↓
Admin Panel ← Views ← Response ← Controller ← Service ← Result

```

### 🔧 **Core Components &amp; Their Roles**

[](#-core-components--their-roles)

#### **Service Provider (`ConfigSwitcherServiceProvider`)**

[](#service-provider-configswitcherserviceprovider)

- **Purpose**: Registers the package with Laravel and bootstraps all components
- **When it runs**: Every time Laravel boots up
- **Key functions**:
    - Binds services to the Laravel container
    - Loads migrations, views, and routes
    - Registers Artisan commands
    - Publishes configuration files

```
// Automatically discovered by Laravel
'providers' => [
    "Mohanad\\ConfigSwitcher\\ConfigSwitcherServiceProvider"
]
```

#### **ConfigManager Service**

[](#configmanager-service)

- **Purpose**: Manages environment variables and configuration files
- **Key methods**:
    - `getEnvConfig()` - Reads and parses `.env` file
    - `updateEnvConfig()` - Updates `.env` file safely with validation
    - `getConfigValues()` - Reads Laravel configuration files
    - `getCurrentState()` - Creates backup of current configuration state
    - `restoreFromState()` - Restores configuration from saved state

#### **SnapshotManager Service**

[](#snapshotmanager-service)

- **Purpose**: Handles configuration snapshots and rollback functionality
- **Key methods**:
    - `createSnapshot()` - Saves current configuration state to database
    - `restoreSnapshot()` - Restores configuration to any previous state
    - `compareWithSnapshot()` - Shows differences between current and saved states
    - `cleanupOldSnapshots()` - Manages storage by removing old snapshots

### 🔄 **How It Works in Practice**

[](#-how-it-works-in-practice)

#### **Snapshot Creation Process**

[](#snapshot-creation-process)

1. **User Action**: User clicks "Create Snapshot" in admin panel
2. **Request Processing**: Controller receives the request and validates input
3. **State Capture**: `SnapshotManager.createSnapshot()` calls `ConfigManager.getCurrentState()`
4. **Data Collection**: System reads current `.env` file and configuration files
5. **State Assembly**: Combines all configuration data into a structured array
6. **Database Storage**: Saves the complete state to `config_snapshots` table
7. **Response**: Returns success confirmation to user

#### **Configuration Update Process**

[](#configuration-update-process)

1. **User Input**: User edits configuration values in admin panel
2. **Validation**: Controller validates all input using custom validation rules
3. **File Reading**: `ConfigManager.updateEnvConfig()` reads current `.env` file
4. **Parsing**: Parses file into key-value pairs
5. **Updating**: Applies new values while preserving file structure
6. **File Writing**: Writes updated configuration back to `.env` file
7. **Response**: Returns success/error status to user

#### **Rollback Process**

[](#rollback-process)

1. **User Selection**: User chooses a snapshot to restore
2. **Confirmation**: System asks for confirmation (can be bypassed with `--force` flag)
3. **Data Retrieval**: `SnapshotManager.restoreSnapshot()` retrieves snapshot data
4. **State Restoration**: `ConfigManager.restoreFromState()` applies saved configuration
5. **File Updates**: Updates `.env` and configuration files with restored values
6. **Verification**: System confirms successful restoration

### 🛡️ **Security &amp; Safety Features**

[](#️-security--safety-features)

#### **Built-in Protections**

[](#built-in-protections)

- **Input Validation**: All inputs are validated using Laravel's validation system
- **Automatic Backups**: Creates snapshots before making any changes
- **Rollback Capability**: Can restore to any previous state instantly
- **IP Restrictions**: Limit access to specific IP addresses
- **User Authentication**: Require login for access to configuration
- **File Permissions**: Safe file operations with proper error handling

#### **Configuration Security**

[](#configuration-security)

```
// In config/config-switcher.php
'security' => [
    'allowed_ips' => ['192.168.1.100'], // Only allow specific IPs
    'require_authentication' => true,    // Require login
    'allowed_users' => ['admin@example.com'], // Restrict to specific users
]
```

### 📊 **Database Schema**

[](#-database-schema)

#### **Snapshots Table Structure**

[](#snapshots-table-structure)

```
CREATE TABLE config_snapshots (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL,
    description TEXT NULL,
    config_data LONGTEXT NOT NULL, -- JSON encoded config state
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL
);
```

#### **Configuration State Structure**

[](#configuration-state-structure)

The `config_data` field stores the complete configuration state as JSON:

```
{
    "env": {
        "APP_NAME": "Laravel",
        "APP_ENV": "production",
        "DB_CONNECTION": "mysql",
        "DB_HOST": "127.0.0.1"
    },
    "config": {
        "app": {
            "name": "Laravel",
            "env": "production",
            "debug": false
        },
        "database": {
            "default": "mysql",
            "connections": {
                "mysql": {
                    "driver": "mysql",
                    "host": "127.0.0.1"
                }
            }
        }
    },
    "timestamp": "2024-01-01T12:00:00Z"
}
```

### 🔌 **Integration with Laravel**

[](#-integration-with-laravel)

#### **Auto-Discovery**

[](#auto-discovery)

Laravel automatically finds and loads your package because of:

- Service provider registration in `composer.json`
- Proper namespace structure following PSR-4
- Laravel package conventions and standards

#### **Service Container Binding**

[](#service-container-binding)

```
// Automatically available throughout your Laravel application
$configManager = app(ConfigManager::class);
$snapshotManager = app(SnapshotManager::class);

// Or use dependency injection
public function __construct(
    private ConfigManager $configManager,
    private SnapshotManager $snapshotManager
) {}
```

### 🚨 **Error Handling &amp; Recovery**

[](#-error-handling--recovery)

#### **Exception Types**

[](#exception-types)

- **`ConfigFileNotFoundException`**: When configuration files are missing
- **`InvalidConfigException`**: When configuration values fail validation
- **`SnapshotNotFoundException`**: When requested snapshot doesn't exist
- **`SnapshotCreationException`**: When snapshot creation fails

#### **Recovery Process**

[](#recovery-process)

```
try {
    $configManager->updateEnvConfig($newConfig);
} catch (ConfigFileNotFoundException $e) {
    // Handle missing .env file
    Log::error('Environment file not found: ' . $e->getMessage());
} catch (InvalidConfigException $e) {
    // Handle invalid configuration values
    Log::error('Invalid configuration: ' . $e->getMessage());
} catch (\Exception $e) {
    // Handle other unexpected errors
    Log::error('Configuration update failed: ' . $e->getMessage());
}
```

### ⚡ **Performance &amp; Scalability**

[](#-performance--scalability)

#### **Optimizations**

[](#optimizations)

- **Lazy Loading**: Services only load when needed
- **Efficient Queries**: Database queries are optimized with proper indexing
- **Memory Management**: Large configurations are handled efficiently
- **Caching**: Configuration values are cached when appropriate

#### **Database Indexing**

[](#database-indexing)

```
-- Optimized queries with proper indexing
CREATE INDEX idx_config_snapshots_name ON config_snapshots(name);
CREATE INDEX idx_config_snapshots_created_at ON config_snapshots(created_at);
```

### 🎯 **Use Cases &amp; Scenarios**

[](#-use-cases--scenarios)

#### **Production Environment Management**

[](#production-environment-management)

1. **Before Deployment**: Create snapshot of current configuration
2. **Update Configuration**: Change environment variables for new release
3. **Testing**: Verify everything works with new configuration
4. **Rollback if Needed**: Instantly restore previous working state

#### **Development Workflow**

[](#development-workflow)

1. **Local Changes**: Test configuration changes in development
2. **Create Snapshot**: Save working configuration state
3. **Experiment**: Try different configuration combinations
4. **Restore**: Go back to working state if experiments fail

#### **Team Collaboration**

[](#team-collaboration)

1. **Configuration Sharing**: Share working configurations with team
2. **Version Control**: Track configuration changes over time
3. **Audit Trail**: See who changed what and when
4. **Compliance**: Maintain configuration history for audits

### 🔄 **Data Flow Examples**

[](#-data-flow-examples)

#### **Creating a Snapshot**

[](#creating-a-snapshot)

 ```
graph TD
    A[User clicks 'Create Snapshot'] --> B[Controller receives request]
    B --> C[Validate input: name, description]
    C --> D[SnapshotManager.createSnapshot()]
    D --> E[ConfigManager.getCurrentState()]
    E --> F[Read .env file]
    E --> G[Read config files]
    F --> H[Parse environment variables]
    G --> I[Parse configuration arrays]
    H --> J[Combine into state array]
    I --> J
    J --> K[Save to database]
    K --> L[Return success response]
```

      Loading #### **Updating Configuration**

[](#updating-configuration)

 ```
graph TD
    A[User edits config values] --> B[Controller validates input]
    B --> C[ConfigManager.updateEnvConfig()]
    C --> D[Read current .env file]
    D --> E[Parse into key-value pairs]
    E --> F[Apply new values]
    F --> G[Validate final configuration]
    G --> H[Write back to .env file]
    H --> I[Return success/error response]
```

      Loading ### 🎉 **Key Benefits**

[](#-key-benefits)

✅ **Safe**: Never lose your configuration - always have rollback capability
✅ **Fast**: Quick configuration updates and instant rollbacks
✅ **Secure**: Built-in security features and validation
✅ **Flexible**: Web interface + CLI commands + RESTful API
✅ **Reliable**: Comprehensive error handling and recovery
✅ **Scalable**: Works with applications of any size
✅ **Maintainable**: Clean, SOLID architecture following Laravel standards

This package essentially gives you **"Git for your configuration"** - you can track changes, create branches (snapshots), and rollback to any previous state, all through a beautiful web interface or powerful command line tools! 🚀

Installation
------------

[](#installation)

You can install the package via Composer:

```
composer require mohanad/laravel-config-switcher
```

### Publish Configuration

[](#publish-configuration)

```
php artisan vendor:publish --provider="Mohanad\ConfigSwitcher\ConfigSwitcherServiceProvider" --tag="config"
```

### Run Migrations

[](#run-migrations)

```
php artisan migrate
```

### Publish Views (Optional)

[](#publish-views-optional)

```
php artisan vendor:publish --provider="Mohanad\ConfigSwitcher\ConfigSwitcherServiceProvider" --tag="views"
```

Configuration
-------------

[](#configuration)

After publishing the configuration file, you can customize the package behavior in `config/config-switcher.php`:

```
return [
    'table_name' => 'config_snapshots',

    'routes' => [
        'prefix' => 'config-switcher',
        'middleware' => ['web'],
    ],

    'security' => [
        'allowed_ips' => [], // Empty array means all IPs are allowed
        'allowed_users' => [], // Empty array means all authenticated users
        'require_authentication' => false,
    ],

    'validation' => [
        'env' => [
            'APP_ENV' => '/^(local|staging|production)$/',
            'APP_DEBUG' => '/^(true|false)$/',
            'DB_CONNECTION' => '/^(mysql|pgsql|sqlite|sqlsrv)$/',
        ],
    ],

    'snapshots' => [
        'max_snapshots' => 50,
        'auto_cleanup' => true,
        'cleanup_threshold' => 10,
    ],
];
```

Usage
-----

[](#usage)

### Web Interface

[](#web-interface)

Access the admin panel at `/config-switcher` (or your configured prefix).

#### Environment Variables

[](#environment-variables)

- View and edit all environment variables from your `.env` file
- Real-time validation with custom rules
- Safe updates with backup functionality

#### Configuration Files

[](#configuration-files)

- Browse and edit Laravel configuration files
- Syntax highlighting and validation
- File-specific settings management

#### Snapshots

[](#snapshots)

- Create snapshots of your current configuration
- Restore to any previous snapshot
- Compare differences between snapshots
- Automatic cleanup of old snapshots

### Artisan Commands

[](#artisan-commands)

#### Create a Snapshot

[](#create-a-snapshot)

```
php artisan config:snapshot "Before Production Deploy" --description="Snapshot before deploying to production"
```

#### List Snapshots

[](#list-snapshots)

```
php artisan config:snapshots --limit=20
```

#### Rollback to Snapshot

[](#rollback-to-snapshot)

```
php artisan config:rollback 5 --force
```

Security
--------

[](#security)

### IP Restrictions

[](#ip-restrictions)

Configure allowed IP addresses in your config file:

```
'security' => [
    'allowed_ips' => ['192.168.1.100', '10.0.0.50'],
],
```

### User Authentication

[](#user-authentication)

Require authentication and restrict to specific users:

```
'security' => [
    'require_authentication' => true,
    'allowed_users' => [1, 2, 'admin@example.com'],
],
```

### Validation Rules

[](#validation-rules)

Define custom validation rules for environment variables:

```
'validation' => [
    'env' => [
        'APP_ENV' => '/^(local|staging|production)$/',
        'CUSTOM_VAR' => function($value) {
            return strlen($value) >= 8;
        },
    ],
],
```

API Endpoints
-------------

[](#api-endpoints)

The package provides RESTful API endpoints for programmatic access:

### Environment Configuration

[](#environment-configuration)

```
POST /config-switcher/env/update
Content-Type: application/json

{
    "config": {
        "APP_NAME": "My App",
        "APP_ENV": "production"
    }
}
```

### Snapshots

[](#snapshots-1)

```
# Create snapshot
POST /config-switcher/snapshots
{
    "name": "Production Backup",
    "description": "Backup before major changes"
}

# Get all snapshots
GET /config-switcher/snapshots

# Restore snapshot
POST /config-switcher/snapshots/restore
{
    "id": 5
}

# Delete snapshot
DELETE /config-switcher/snapshots
{
    "id": 5
}
```

Advanced Usage
--------------

[](#advanced-usage)

### Programmatic Access

[](#programmatic-access)

```
use Mohanad\ConfigSwitcher\Services\ConfigManager;
use Mohanad\ConfigSwitcher\Services\SnapshotManager;

// Get config manager
$configManager = app(ConfigManager::class);

// Update environment variables
$configManager->updateEnvConfig([
    'APP_NAME' => 'New App Name',
    'APP_ENV' => 'production'
]);

// Create snapshot
$snapshotManager = app(SnapshotManager::class);
$snapshot = $snapshotManager->createSnapshot('API Backup', 'Created via API');

// Restore snapshot
$snapshotManager->restoreSnapshot($snapshot->id);
```

### Custom Validation

[](#custom-validation)

```
use Mohanad\ConfigSwitcher\Services\ConfigManager;

$configManager = app(ConfigManager::class);

$rules = [
    'APP_ENV' => '/^(local|staging|production)$/',
    'DB_PASSWORD' => function($value) {
        return strlen($value) >= 12 && preg_match('/[A-Za-z0-9@#$%^&+=]/', $value);
    },
];

$configManager->validateConfig($config, $rules);
```

Testing
-------

[](#testing)

Run the test suite:

```
composer test
```

The package includes comprehensive tests for:

- Configuration management
- Snapshot functionality
- API endpoints
- Validation rules
- Security features

Contributing
------------

[](#contributing)

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

If you discover a security vulnerability, please send an e-mail to . All security vulnerabilities will be promptly addressed.

License
-------

[](#license)

This package is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).

Changelog
---------

[](#changelog)

### 1.0.0

[](#100)

- Initial release
- Environment variable management
- Configuration file management
- Snapshot and rollback functionality
- Web admin panel
- Artisan commands
- Security features
- Comprehensive testing

Support
-------

[](#support)

For support, please open an issue on GitHub or contact .

---

**Note**: This package is designed for development and staging environments. Use with caution in production environments and always backup your configuration before making changes.

###  Health Score

15

—

LowBetter than 3% of packages

Maintenance43

Moderate activity, may be stable

Popularity0

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity13

Early-stage or recently created project

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/d6b90369f1d9441a08ec97072155df04489deccc4ee55d93608ed9f88670404c?d=identicon)[mohanadhilles](/maintainers/mohanadhilles)

### Embed Badge

![Health badge](/badges/mohanad-laravel-config-switcher/health.svg)

```
[![Health](https://phpackages.com/badges/mohanad-laravel-config-switcher/health.svg)](https://phpackages.com/packages/mohanad-laravel-config-switcher)
```

###  Alternatives

[afsakar/filament-leaflet-map-picker

A Filament Forms component that provides an interactive Leaflet map for selecting and storing geographical coordinates.

387.2k](/packages/afsakar-filament-leaflet-map-picker)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
