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

Laravel Settings Laravel Package

spatie/laravel-settings

Strongly typed app settings for Laravel stored in databases, Redis, and more. Define settings classes with typed properties, inject them via the container, and read/update values with simple save() calls. Includes migrations, caching, and multiple repositories.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Steps to First Use
1. **Installation**
   ```bash
   composer require spatie/laravel-settings
   php artisan vendor:publish --provider="Spatie\LaravelSettings\LaravelSettingsServiceProvider" --tag="migrations"
   php artisan vendor:publish --provider="Spatie\LaravelSettings\LaravelSettingsServiceProvider" --tag="config"
   php artisan migrate
  1. Create a Settings Class

    php artisan make:setting GeneralSettings --group=general
    

    This generates a class in app/Settings/GeneralSettings.php:

    class GeneralSettings extends Settings {
        public string $site_name = 'My App';
        public bool $site_active = true;
    
        public static function group(): string { return 'general'; }
    }
    
  2. Register the Settings Class Add the class to config/settings.php under the settings array:

    'settings' => [
        \App\Settings\GeneralSettings::class,
    ],
    
  3. Create a Migration

    php artisan make:settings-migration CreateGeneralSettings
    

    Define defaults in database/settings/YYYY_MM_DD_CreateGeneralSettings.php:

    public function up(): void {
        $this->migrator->add('general.site_name', 'My App');
        $this->migrator->add('general.site_active', true);
    }
    

    Run the migration:

    php artisan migrate
    
  4. Use in Code Inject the settings class into a controller or service:

    class HomeController {
        public function index(GeneralSettings $settings) {
            return view('home', [
                'siteName' => $settings->site_name,
                'isActive' => $settings->site_active,
            ]);
        }
    }
    

Implementation Patterns

Core Workflows

  1. Dependency Injection

    • Best Practice: Always inject settings classes via constructor or method parameters.
    • Example:
      class FeatureToggleService {
          public function __construct(public FeatureSettings $settings) {}
          public function isEnabled(string $feature): bool {
              return $this->settings->features[$feature] ?? false;
          }
      }
      
  2. Grouping Settings

    • Use Case: Organize settings by domain (e.g., PaymentSettings, EmailSettings).
    • Example:
      class PaymentSettings extends Settings {
          public string $gateway = 'stripe';
          public int $timeout = 30;
      
          public static function group(): string { return 'payment'; }
      }
      
  3. Repository Selection

    • Use Case: Use Redis for high-performance settings (e.g., caching).
    • Example:
      class CacheSettings extends Settings {
          public static function repository(): string { return 'redis'; }
          public static function group(): string { return 'cache'; }
      }
      
  4. Validation

    • Best Practice: Use Form Requests to validate updates.
    • Example:
      class UpdateGeneralSettingsRequest extends FormRequest {
          public function rules(): array {
              return [
                  'site_name' => 'required|string|max:255',
                  'site_active' => 'boolean',
              ];
          }
      }
      
  5. Dynamic Defaults

    • Use Case: Set defaults based on environment.
    • Example:
      class AppSettings extends Settings {
          public string $env = app()->environment();
          public bool $debug = app()->isLocal();
      }
      

Integration Tips

  • Cache Settings: Enable caching in config/settings.php for performance:

    'cache' => [
        'enabled' => env('SETTINGS_CACHE_ENABLED', true),
        'store' => 'redis',
        'ttl' => 60, // Cache for 60 seconds
    ],
    
  • Custom Casts: Extend for complex types (e.g., Collection, Carbon):

    use Spatie\LaravelSettings\SettingsCasts\SettingsCast;
    
    class JsonArrayCast implements SettingsCast {
        public function get($model, string $key, $value, array $attributes) {
            return json_decode($value, true);
        }
        public function set($model, string $key, $value, array $attributes) {
            return json_encode($value);
        }
    }
    

    Register in config/settings.php:

    'global_casts' => [
        'array' => \App\SettingsCasts\JsonArrayCast::class,
    ],
    
  • Event Listeners: Trigger actions on setting updates:

    class SettingsUpdatedListener {
        public function handle(SettingsUpdated $event) {
            if ($event->settings instanceof GeneralSettings) {
                Log::info('General settings updated', $event->changes);
            }
        }
    }
    

    Register in EventServiceProvider:

    protected $listen = [
        SettingsUpdated::class => [SettingsUpdatedListener::class],
    ];
    

Gotchas and Tips

Common Pitfalls

  1. Missing Migrations

    • Issue: Forgetting to run migrations after adding/removing settings properties.
    • Fix: Always run php artisan migrate after modifying settings classes or migrations.
    • Tip: Use php artisan settings:refresh to regenerate migrations from settings classes.
  2. Circular Dependencies

    • Issue: Settings classes depending on each other (e.g., A uses B, B uses A).
    • Fix: Resolve dependencies via constructor injection or lazy loading:
      class A {
          public function __construct(public ?B $b = null) {}
      }
      
  3. Repository Mismatches

    • Issue: Settings class not found because the wrong repository is configured.
    • Fix: Explicitly set the repository in the settings class:
      public static function repository(): string { return 'custom_repo'; }
      
    • Debug: Check config/settings.php for repository configurations.
  4. Type Safety

    • Issue: Properties not matching their declared types (e.g., string vs int).
    • Fix: Use custom casts for complex types or validate in Form Requests.
  5. Cache Invalidation

    • Issue: Stale cached settings after updates.
    • Fix: Clear cache manually or use Settings::forgetCache():
      Settings::forgetCache(GeneralSettings::class);
      

Debugging Tips

  • Inspect Settings:
    $settings = app(GeneralSettings::class);
    dd($settings->toArray()); // Dump all settings
    
  • Check Repository:
    $repository = app(GeneralSettings::class)->getRepository();
    dd($repository->getAll());
    
  • Enable Logging: Add to config/settings.php:
    'debug' => env('SETTINGS_DEBUG', false),
    
    Logs will appear in storage/logs/laravel-settings.log.

Extension Points

  1. Custom Repositories

    • Implement Spatie\LaravelSettings\SettingsRepositories\SettingsRepository:
      class ApiSettingsRepository implements SettingsRepository {
          public function get(string $group, string $key, $default = null) { ... }
          public function set(string $group, string $key, $value) { ... }
          public function delete(string $group, string $key) { ... }
      }
      
    • Register in config/settings.php:
      'repositories' => [
          'api' => [
              'type' => \App\SettingsRepositories\ApiSettingsRepository::class,
          ],
      ],
      
  2. Custom Migrations

    • Extend Spatie\LaravelSettings\Migrations\SettingsMigration for custom logic:
      class CustomSettingsMigration extends SettingsMigration {
          protected function migrate(): void {
              $this->migrator->add('custom.group.key', 'default');
              // Custom logic here
          }
      }
      
  3. Dynamic Settings

    • Use Settings::get() for runtime access:
      $value = Settings::get('group.key', 'default');
      Settings::set('group.key', $newValue);
      
  4. Environment-Specific Settings

    • Override defaults in migrations based on environment:
      public function up(): void {
          $this->migrator->add('app.debug', app()->isLocal());
      }
      

Performance Quirks

  • Cache Overhead: Enabling cache adds a small TTL-based delay. Disable for development:
    'cache' => ['enabled' => env('SETTINGS_CACHE_ENABLED', false)],
    
  • Redis Latency: Redis repositories add network overhead. Use for non-critical settings.
  • Database Locks: Concurrent writes to the same settings group may cause locks. Use Redis for high-contention settings.

Security Tips

  • **
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata