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 application settings for Laravel. Define settings classes with typed properties, store values in a repository (database, Redis, etc.), inject settings via the container, and update them easily with $settings->save().

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to Begin

  1. Installation Run composer require spatie/laravel-settings and publish the migrations and config:

    php artisan vendor:publish --provider="Spatie\LaravelSettings\LaravelSettingsServiceProvider" --tag="migrations"
    php artisan vendor:publish --provider="Spatie\LaravelSettings\LaravelSettingsServiceProvider" --tag="config"
    

    Run migrations:

    php artisan migrate
    
  2. Create a Settings Class Use the Artisan command to scaffold a new settings class:

    php artisan make:setting GeneralSettings --group=general
    

    This generates a class like:

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

    'settings' => [
        GeneralSettings::class,
    ],
    
  4. Create a Migration Define default values for your settings:

    php artisan make:settings-migration CreateGeneralSettings
    

    Populate defaults in the migration:

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

    Run the migration:

    php artisan migrate
    
  5. First Usage Inject the settings class into a controller or service:

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

Implementation Patterns

Dependency Injection

  • Automatic Registration: The package registers all settings classes in Laravel’s container, allowing seamless dependency injection.
  • Usage in Controllers/Jobs:
    public function updateSettings(GeneralSettings $settings, Request $request) {
        $settings->site_name = $request->input('site_name');
        $settings->save();
    }
    

Repository Selection

  • Default Repository: Configured in config/settings.php under default_repository.
  • Custom Repository per Class: Override the default by implementing repository():
    public static function repository(): ?string {
        return 'redis';
    }
    

Caching

  • Enable caching in config/settings.php:
    'cache' => [
        'enabled' => true,
        'store' => 'redis',
        'ttl' => 60, // Cache TTL in minutes
    ],
    
  • Cache Invalidation: Settings are automatically invalidated after updates.

Grouping and Organization

  • Grouped Settings: Use group() to logically separate settings (e.g., general, payment, notifications).
  • Multi-Group Workflows:
    class PaymentSettings extends Settings {
        public static function group(): string {
            return 'payment';
        }
    }
    

Form Requests

  • Validation: Use Form Requests to validate settings updates:
    class GeneralSettingsRequest extends FormRequest {
        public function rules(): array {
            return [
                'site_name' => 'required|string|max:255',
                'site_active' => 'boolean',
            ];
        }
    }
    

Dynamic Settings

  • Runtime Updates: Modify settings dynamically without redeploying:
    $settings = app(GeneralSettings::class);
    $settings->site_active = false;
    $settings->save();
    

Gotchas and Tips

Pitfalls

  1. Missing Migrations:

    • Forgetting to run migrations after creating/updating settings classes will result in missing defaults or errors.
    • Fix: Always run php artisan migrate after modifying settings migrations.
  2. Circular Dependencies:

    • Avoid injecting settings classes into other settings classes to prevent circular dependencies.
    • Fix: Use service locator (app(GeneralSettings::class)) sparingly.
  3. Repository Mismatches:

    • If a settings class specifies a non-existent repository, it will throw an error.
    • Fix: Ensure repositories are defined in config/settings.php or use the default.
  4. Cache Stale Data:

    • If caching is enabled but not invalidated properly, stale data may persist.
    • Fix: Disable caching during development ('enabled' => false) or manually clear the cache:
      php artisan cache:clear
      
  5. Type Safety:

    • The package relies on PHP’s type system. Incorrect types (e.g., assigning a string to a boolean property) may cause runtime errors.
    • Fix: Use Form Requests or manual type checks before saving.

Debugging Tips

  1. Check Repository Contents:

    • Inspect the database or Redis for settings data:
      php artisan tinker
      >>> \Spatie\LaravelSettings\Settings::all();
      
  2. Log Settings Updates:

    • Add logging to track changes:
      $settings->save();
      \Log::info('Settings updated', ['group' => $settings->group(), 'data' => $settings->toArray()]);
      
  3. Validate Migrations:

    • Test migrations in a staging environment before deploying to production.

Extension Points

  1. Custom Repositories:

    • Extend Spatie\LaravelSettings\SettingsRepositories\SettingsRepository to support new storage backends (e.g., S3, DynamoDB).
  2. Custom Casts:

    • Add custom casts for complex types (e.g., arrays, objects) in config/settings.php:
      'global_casts' => [
          MyCustomClass::class => MyCustomCast::class,
      ],
      
  3. Event Listeners:

    • Listen for settings updates via events:
      use Spatie\LaravelSettings\Events\SettingsUpdated;
      
      SettingsUpdated::dispatch($settings);
      
  4. Custom Encoders/Decoders:

    • Override JSON encoding/decoding for specific needs:
      'encoder' => function ($value) {
          return serialize($value);
      },
      'decoder' => 'unserialize',
      

Performance Tips

  1. Batch Updates:

    • For bulk updates, use transactions to avoid race conditions:
      \DB::transaction(function () use ($settings) {
          $settings->property1 = $value1;
          $settings->property2 = $value2;
          $settings->save();
      });
      
  2. Selective Loading:

    • Use Settings::get() to fetch only specific properties:
      $siteName = Settings::get(GeneralSettings::class, 'site_name');
      
  3. Disable Caching in Development:

    • Set 'enabled' => false in config/settings.php for faster iteration.

Common Workflows

  1. Feature Flags:

    class FeatureFlags extends Settings {
        public bool $new_ui_enabled;
        public bool $experimental_api;
    
        public static function group(): string {
            return 'features';
        }
    }
    

    Usage:

    if (app(FeatureFlags::class)->new_ui_enabled) {
        // Enable new UI
    }
    
  2. Multi-Tenant Settings:

    • Use middleware to load tenant-specific settings:
      class TenantSettingsMiddleware {
          public function handle($request, Closure $next) {
              $settings = app(TenantSettings::class)->forTenant(auth()->id());
              // ...
          }
      }
      
  3. Environment-Specific Settings:

    • Override settings per environment using .env or config files:
      if (app()->environment('staging')) {
          $settings->debug_mode = true;
      }
      
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.
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
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope