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

Settings Main Laravel Package

baks-dev/settings-main

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require baks-dev/settings-main
   php artisan vendor:publish --provider="BaksDev\SettingsMain\SettingsMainServiceProvider" --tag="settings-main-config"
  • Publishes default config to config/settings-main.php.
  1. Database Migration:

    php artisan migrate
    
    • Creates tables for settings storage (e.g., settings, setting_groups).
  2. First Use Case: Define a setting in config/settings-main.php:

    'settings' => [
        'app' => [
            'maintenance_mode' => [
                'type' => 'boolean',
                'default' => false,
                'label' => 'Enable Maintenance Mode',
            ],
        ],
    ],
    

    Then register it via a console command or manually in the database.


Where to Look First

  • Config File: config/settings-main.php – Centralized settings definition.
  • Service Provider: BaksDev\SettingsMain\SettingsMainServiceProvider – Bootstraps the package.
  • Console Commands:
    • baks:assets:install – Installs default assets (if applicable).
    • baks:settings:flush – Clears cached settings (debugging).
  • Migrations: database/migrations/[timestamp]_create_settings_tables.php – Schema for settings storage.

First Practical Task

Enable a toggleable feature (e.g., "Dark Mode"):

  1. Add to config/settings-main.php:
    'features' => [
        'dark_mode' => [
            'type' => 'boolean',
            'default' => false,
            'label' => 'Enable Dark Mode',
        ],
    ],
    
  2. Access it in code:
    $darkModeEnabled = setting('features.dark_mode');
    
  3. Create a toggle UI using the package’s built-in form helpers (if available) or a custom blade view.

Implementation Patterns

Core Workflows

1. Defining Settings

  • Centralized Configuration: Use config/settings-main.php to define all settings hierarchically (e.g., app.maintenance_mode).

    'app' => [
        'maintenance_mode' => [
            'type' => 'boolean',
            'default' => false,
            'validation' => 'required|boolean',
        ],
    ],
    
    • Types: string, boolean, integer, array, json (custom types can be extended via events).
  • Dynamic Registration: Register settings programmatically via the SettingsManager facade:

    use BaksDev\SettingsMain\Facades\SettingsManager;
    
    SettingsManager::register([
        'new_setting' => [
            'type' => 'string',
            'default' => 'default_value',
        ],
    ]);
    

2. Accessing Settings

  • Facade:
    $value = setting('app.maintenance_mode'); // Returns boolean
    
  • Environment Fallback: Settings can fall back to .env if configured (check config/settings-main.php for env_fallback option).

3. Updating Settings

  • Manual Updates:
    setting('app.maintenance_mode', true);
    
  • Mass Assignment:
    setting()->update([
        'app.maintenance_mode' => true,
        'features.dark_mode' => true,
    ]);
    
  • User Input: Use the package’s form helpers (if provided) or validate with Laravel’s Validator:
    $validator = Validator::make($request->all(), [
        'maintenance_mode' => 'required|boolean|settings:app.maintenance_mode',
    ]);
    

4. Grouped Settings

  • Hierarchical Access:
    // Access a nested setting
    $value = setting('features.dark_mode');
    
    // Update a group
    setting()->updateGroup('features', ['dark_mode' => true]);
    
  • Scoped Settings: Useful for multi-tenancy or context-specific settings (e.g., setting('tenant-123.app.maintenance_mode')).

5. Caching

  • Automatic Caching: Settings are cached by default. Clear with:
    php artisan baks:settings:flush
    
  • Cache Tags: Use setting()->flushTag('group-name') to invalidate specific groups.

Integration Tips

Laravel Features

  • Service Providers: Bind settings to the container for dependency injection:
    $this->app->singleton('settings', function () {
        return setting();
    });
    
  • Events: Listen for setting updates:
    event(new SettingUpdated('app.maintenance_mode', true));
    
  • Policies: Restrict setting access:
    class SettingPolicy {
        public function update(User $user, string $key) {
            return $user->isAdmin();
        }
    }
    

Customization

  • Extend Setting Types: Create custom types by implementing BaksDev\SettingsMain\Contracts\SettingType:

    class ColorSetting implements SettingType {
        public function validate($value) {
            return preg_match('/^#[0-9A-F]{6}$/i', $value);
        }
    }
    

    Register via SettingsManager::extend('color', ColorSetting::class).

  • Custom Storage: Override the default Eloquent storage by binding a custom repository:

    $this->app->bind(
        \BaksDev\SettingsMain\Contracts\SettingRepository::class,
        \App\Repositories\CustomSettingRepository::class
    );
    

Admin Panels

  • Backoffice Integration: Use the package’s built-in admin routes (if available) or integrate with:
    • Filament: Create a resource for Setting.
    • Nova: Add a custom card or tool.
    • Custom Blade Views:
      @foreach(setting()->groups() as $group)
          <h3>{{ $group['label'] }}</h3>
          @foreach($group['settings'] as $key => $setting)
              <div>
                  <label>{{ $setting['label'] }}</label>
                  <input type="{{ $setting['type'] }}" name="settings[{{ $key }}]">
              </div>
          @endforeach
      @endforeach
      

Gotchas and Tips

Pitfalls

  1. Case Sensitivity: Setting keys are case-sensitive (e.g., app.MaintenanceModeapp.maintenance_mode). Use consistent naming.

  2. Validation Bypass: Direct database updates (e.g., via raw SQL) skip Laravel validation. Always use setting()->update().

  3. Caching Issues:

    • Clear cache after manual database changes:
      php artisan baks:settings:flush
      
    • Avoid overusing setting()->flush() in production; use tags instead.
  4. Default Values: Defaults in config/settings-main.php are not applied retroactively to existing settings. Use migrations or manual updates to reset values.

  5. Type Mismatches: Storing a string as an integer may cause silent failures. Validate types explicitly:

    if (!is_bool(setting('app.maintenance_mode'))) {
        setting('app.maintenance_mode', false);
    }
    
  6. Migration Conflicts: If manually editing migrations, ensure timestamps match the package’s default migrations to avoid conflicts.


Debugging

  1. Log Settings: Dump all settings for debugging:

    \Log::info('All settings:', setting()->all());
    

    Or use Tinker:

    php artisan tinker
    >>> setting()->all();
    
  2. Check for Overrides: Settings can be overridden by:

    • Environment variables (if env_fallback is true).
    • Cache (check file or redis cache).
    • Manual database entries (priority: DB > Cache > Config).
  3. Event Listeners: Debug setting updates via events:

    SettingUpdated::dispatch($key, $value);
    

    Listen in EventServiceProvider:

    protected $listen = [
        SettingUpdated::class => [
            \App\Listeners\LogSettingChange::class,
        ],
    ];
    

Configuration Quirks

  1. config/settings-main.php Options:

    • cache_driver: Override the default cache driver (e.g., redis).
    • env_fallback: Enable to fall back to .env (e.g., SETTINGS_APP_MAINTENANCE_MODE=true).
    • default_group: Set a default group for bulk operations.
  2. Database Schema: The package uses three tables by default:

    • settings: Stores key-value pairs.
    • setting_groups: Groups settings hierarchically.
    • setting_types: Defines custom types (if extended).
  3. Performance:

    • For large-scale apps, consider denormalizing settings into a single table with json columns.
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