mohanad / laravel-config-switcher
A Laravel package for managing configuration and environment settings with snapshot/rollback functionality
Installs: 0
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 0
Forks: 0
Open Issues: 0
pkg:composer/mohanad/laravel-config-switcher
Requires
- php: ^8.1
- illuminate/console: ^10.0|^11.0
- illuminate/database: ^10.0|^11.0
- illuminate/support: ^10.0|^11.0
Requires (Dev)
- mockery/mockery: ^1.4
- orchestra/testbench: ^8.0|^9.0
- phpunit/phpunit: ^10.0
This package is auto-updated.
Last update: 2026-01-03 22:17:18 UTC
README
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
- ๐ง Environment Management: Safely update
.envfile 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
๐๏ธ 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 & Their Roles
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
- Purpose: Manages environment variables and configuration files
- Key methods:
getEnvConfig()- Reads and parses.envfileupdateEnvConfig()- Updates.envfile safely with validationgetConfigValues()- Reads Laravel configuration filesgetCurrentState()- Creates backup of current configuration staterestoreFromState()- Restores configuration from saved state
SnapshotManager Service
- Purpose: Handles configuration snapshots and rollback functionality
- Key methods:
createSnapshot()- Saves current configuration state to databaserestoreSnapshot()- Restores configuration to any previous statecompareWithSnapshot()- Shows differences between current and saved statescleanupOldSnapshots()- Manages storage by removing old snapshots
๐ How It Works in Practice
Snapshot Creation Process
- User Action: User clicks "Create Snapshot" in admin panel
- Request Processing: Controller receives the request and validates input
- State Capture:
SnapshotManager.createSnapshot()callsConfigManager.getCurrentState() - Data Collection: System reads current
.envfile and configuration files - State Assembly: Combines all configuration data into a structured array
- Database Storage: Saves the complete state to
config_snapshotstable - Response: Returns success confirmation to user
Configuration Update Process
- User Input: User edits configuration values in admin panel
- Validation: Controller validates all input using custom validation rules
- File Reading:
ConfigManager.updateEnvConfig()reads current.envfile - Parsing: Parses file into key-value pairs
- Updating: Applies new values while preserving file structure
- File Writing: Writes updated configuration back to
.envfile - Response: Returns success/error status to user
Rollback Process
- User Selection: User chooses a snapshot to restore
- Confirmation: System asks for confirmation (can be bypassed with
--forceflag) - Data Retrieval:
SnapshotManager.restoreSnapshot()retrieves snapshot data - State Restoration:
ConfigManager.restoreFromState()applies saved configuration - File Updates: Updates
.envand configuration files with restored values - Verification: System confirms successful restoration
๐ก๏ธ Security & Safety Features
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
// 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
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
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
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
// 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 & Recovery
Exception Types
ConfigFileNotFoundException: When configuration files are missingInvalidConfigException: When configuration values fail validationSnapshotNotFoundException: When requested snapshot doesn't existSnapshotCreationException: When snapshot creation fails
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 & Scalability
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
-- 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 & Scenarios
Production Environment Management
- Before Deployment: Create snapshot of current configuration
- Update Configuration: Change environment variables for new release
- Testing: Verify everything works with new configuration
- Rollback if Needed: Instantly restore previous working state
Development Workflow
- Local Changes: Test configuration changes in development
- Create Snapshot: Save working configuration state
- Experiment: Try different configuration combinations
- Restore: Go back to working state if experiments fail
Team Collaboration
- Configuration Sharing: Share working configurations with team
- Version Control: Track configuration changes over time
- Audit Trail: See who changed what and when
- Compliance: Maintain configuration history for audits
๐ Data Flow Examples
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
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
โ
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
You can install the package via Composer:
composer require mohanad/laravel-config-switcher
Publish Configuration
php artisan vendor:publish --provider="Mohanad\ConfigSwitcher\ConfigSwitcherServiceProvider" --tag="config"
Run Migrations
php artisan migrate
Publish Views (Optional)
php artisan vendor:publish --provider="Mohanad\ConfigSwitcher\ConfigSwitcherServiceProvider" --tag="views"
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
Web Interface
Access the admin panel at /config-switcher (or your configured prefix).
Environment Variables
- View and edit all environment variables from your
.envfile - Real-time validation with custom rules
- Safe updates with backup functionality
Configuration Files
- Browse and edit Laravel configuration files
- Syntax highlighting and validation
- File-specific settings management
Snapshots
- Create snapshots of your current configuration
- Restore to any previous snapshot
- Compare differences between snapshots
- Automatic cleanup of old snapshots
Artisan Commands
Create a Snapshot
php artisan config:snapshot "Before Production Deploy" --description="Snapshot before deploying to production"
List Snapshots
php artisan config:snapshots --limit=20
Rollback to Snapshot
php artisan config:rollback 5 --force
Security
IP Restrictions
Configure allowed IP addresses in your config file:
'security' => [ 'allowed_ips' => ['192.168.1.100', '10.0.0.50'], ],
User Authentication
Require authentication and restrict to specific users:
'security' => [ 'require_authentication' => true, 'allowed_users' => [1, 2, 'admin@example.com'], ],
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
The package provides RESTful API endpoints for programmatic access:
Environment Configuration
POST /config-switcher/env/update Content-Type: application/json { "config": { "APP_NAME": "My App", "APP_ENV": "production" } }
Snapshots
# 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
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
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
Run the test suite:
composer test
The package includes comprehensive tests for:
- Configuration management
- Snapshot functionality
- API endpoints
- Validation rules
- Security features
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Security Vulnerabilities
If you discover a security vulnerability, please send an e-mail to mohanad@example.com. All security vulnerabilities will be promptly addressed.
License
This package is open-sourced software licensed under the MIT license.
Changelog
1.0.0
- Initial release
- Environment variable management
- Configuration file management
- Snapshot and rollback functionality
- Web admin panel
- Artisan commands
- Security features
- Comprehensive testing
Support
For support, please open an issue on GitHub or contact mohanad@example.com.
Note: This package is designed for development and staging environments. Use with caution in production environments and always backup your configuration before making changes.