Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Module Environments Laravel Package

cvepdb-cms/module-environments

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require cvepdb-cms/module-environments
    

    Publish the migration and config:

    php artisan vendor:publish --provider="Cvepdb\Environments\EnvironmentsServiceProvider" --tag="migrations"
    php artisan vendor:publish --provider="Cvepdb\Environments\EnvironmentsServiceProvider" --tag="config"
    

    Run migrations:

    php artisan migrate
    
  2. First Use Case Create an environment via Tinker or a controller:

    use Cvepdb\Environments\Models\Environment;
    
    $env = Environment::create([
        'name' => 'Production',
        'domain' => 'app.example.com',
        'is_active' => true,
        'variables' => json_encode(['APP_ENV' => 'production']),
    ]);
    
  3. Key Classes

    • Environment Model: Core model for managing environments.
    • EnvironmentVariable Model: Stores key-value pairs for environment variables.
    • EnvironmentService: Facade for common operations (e.g., Environments::findActive()).

Implementation Patterns

Common Workflows

  1. Environment Management

    • Create/Update:
      $env = Environment::updateOrCreate(
          ['domain' => 'staging.example.com'],
          ['name' => 'Staging', 'is_active' => false]
      );
      
    • Toggle Active Status:
      $env = Environment::find(1);
      $env->toggleActive(); // Toggles `is_active` and deactivates others
      
  2. Variable Handling

    • Add/Update Variables:
      $env->variables()->sync([
          ['key' => 'DB_HOST', 'value' => 'localhost'],
          ['key' => 'DEBUG', 'value' => 'false'],
      ]);
      
    • Retrieve Variables:
      $variables = $env->variables()->pluck('value', 'key')->toArray();
      
  3. Domain-Based Routing Integrate with Laravel’s routing to switch behavior per environment:

    Route::domain('{domain}')->group(function () {
        $env = Environments::findByDomain(request()->domain());
        if ($env) {
            config(['app.env' => $env->name]);
            // Load environment-specific config
        }
    });
    
  4. Environment-Aware Config Dynamically load config based on the active environment:

    $env = Environments::getActive();
    config(["services.{$env->name}" => $env->variables()->pluck('value', 'key')->toArray()]);
    

Integration Tips

  • Middleware: Create middleware to resolve the active environment on each request:
    class SetEnvironmentMiddleware
    {
        public function handle($request, Closure $next) {
            $env = Environments::findByDomain($request->getHost());
            if ($env) {
                app()->singleton('active_environment', $env);
            }
            return $next($request);
        }
    }
    
  • Service Providers: Bind the active environment to the container:
    $this->app->bind('active_environment', function () {
        return Environments::getActive();
    });
    
  • Artisan Commands: Extend commands to work with environments:
    $env = Environments::find($id);
    Artisan::call('config:clear');
    Artisan::call('cache:clear');
    $env->refreshCache(); // Hypothetical method
    

Gotchas and Tips

Pitfalls

  1. Domain Conflicts

    • Ensure domain fields are unique. Use Laravel’s unique validation rule:
      'domain' => 'required|unique:environments,domain',
      
    • Fix: Add a custom validator or use updateOrCreate with domain checks.
  2. Variable Serialization

    • The variables field is stored as JSON. Avoid circular references or large payloads.
    • Tip: Use json_encode($array, JSON_THROW_ON_ERROR) for validation.
  3. Active Environment Logic

    • The toggleActive() method deactivates all other environments. Test this in staging:
      $env->toggleActive(); // Ensure no race conditions in multi-user setups
      
  4. Caching

    • Environment variables may not update immediately if cached. Clear caches after updates:
      $env->save();
      Cache::forget('env_variables');
      

Debugging

  • Missing Environments: Verify the domain matches the request host exactly (case-sensitive).
  • Variable Overrides: Use dd($env->variables) to inspect raw data.
  • Migration Issues: Check for reserved column names (e.g., created_at conflicts).

Extension Points

  1. Custom Variables Extend the EnvironmentVariable model to add metadata:

    class EnvironmentVariable extends \Cvepdb\Environments\Models\EnvironmentVariable
    {
        protected $casts = [
            'is_sensitive' => 'boolean',
        ];
    }
    
  2. Environment Events Listen for environment changes:

    Event::listen(EnvironmentUpdated::class, function ($env) {
        Log::info("Environment {$env->name} updated");
    });
    
  3. API Endpoints Expose environments via API (e.g., for dynamic config):

    Route::get('/api/environments', function () {
        return Environments::all()->with('variables');
    });
    
  4. Testing Use factories or seeders to mock environments:

    // database/factories/EnvironmentFactory.php
    $factory->define(Environment::class, function (Faker $faker) {
        return [
            'name' => $faker->word,
            'domain' => $faker->domainName,
            'is_active' => false,
        ];
    });
    

Config Quirks

  • Default Values: The config/environments.php file may define defaults. Override as needed:
    'defaults' => [
        'is_active' => false,
        'variables' => ['APP_ENV' => env('APP_ENV')],
    ],
    
  • Environment-Specific Config: Load config dynamically:
    $env = Environments::getActive();
    $this->mergeConfigFrom("config/environments/{$env->name}.php");
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours