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

Model Settings For Laravel Laravel Package

chapdel/model-settings-for-laravel

Attach flexible key/value settings to any Eloquent model in Laravel. Store, retrieve, and update per-model preferences with a simple API and database table, keeping configuration close to the data it belongs to. PHP 8+ compatible.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require chapdel/model-settings-for-laravel
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="Chapdel\ModelSettings\ServiceProvider"
    
  2. Define a Settings Model Extend Chapdel\ModelSettings\Settings and register it in config/model-settings.php:

    'models' => [
        'App\Models\SiteSettings' => [
            'key' => 'site',
            'guard' => null, // or 'web', 'api', etc.
        ],
    ],
    
  3. First Use Case: Fetching Settings

    use App\Models\SiteSettings;
    
    // Get all settings
    $settings = SiteSettings::get();
    
    // Get a single setting
    $logo = SiteSettings::get('logo');
    

Implementation Patterns

Common Workflows

  1. Caching for Performance Enable caching in config/model-settings.php:

    'cache' => true,
    

    Clear cache manually when needed:

    php artisan model-settings:clear-cache
    
  2. Scoped Settings (Multi-Tenant) Use the guard option to scope settings by user/tenant:

    // In a controller/middleware
    SiteSettings::setGuard('admin');
    $adminSettings = SiteSettings::get('admin_panel');
    
  3. Validation & Defaults Define defaults in the model’s $casts or $attributes:

    protected $casts = [
        'logo' => 'string',
        'maintenance_mode' => 'boolean',
    ];
    
    // Fallback defaults
    public static function defaults()
    {
        return [
            'logo' => 'default-logo.png',
            'maintenance_mode' => false,
        ];
    }
    
  4. Dynamic Updates Update settings via API or admin panel:

    SiteSettings::set('maintenance_mode', true);
    SiteSettings::save(); // Persist changes
    
  5. Event Listeners Listen for setting changes (e.g., broadcast updates):

    SiteSettings::set('theme', 'dark');
    event(new SettingsUpdated(SiteSettings::class, 'theme'));
    

Gotchas and Tips

Pitfalls & Debugging

  1. Cache Invalidation

    • Forgetting to clear cache after updates:
      php artisan model-settings:clear-cache
      
    • Tip: Use php artisan model-settings:clear-cache in a post-update hook (e.g., after SettingsUpdated event).
  2. Guard Mismatches

    • Settings may return null if the guard isn’t set correctly.
    • Fix: Explicitly set the guard before fetching:
      SiteSettings::setGuard('web');
      $settings = SiteSettings::get();
      
  3. Database Schema

    • The package assumes a settings table with key, value, and guard columns.
    • Migration Tip: Run the provided migration if missing:
      php artisan vendor:publish --tag="model-settings-migrations"
      php artisan migrate
      
  4. Type Casting Issues

    • Custom casts (e.g., JSON, dates) may fail silently.
    • Debug: Check dd($settings->toArray()) to verify data types.
  5. Concurrency Conflicts

    • Rapid updates may overwrite changes.
    • Solution: Use transactions or optimistic locking:
      DB::transaction(function () {
          SiteSettings::set('key', 'value');
          SiteSettings::save();
      });
      

Extension Points

  1. Custom Storage Override the default storage (e.g., Redis) by binding a custom repository:

    $this->app->bind(
        \Chapdel\ModelSettings\Repositories\SettingsRepository::class,
        \App\Repositories\CustomSettingsRepository::class
    );
    
  2. Encrypted Fields Use Laravel’s encryption for sensitive settings:

    protected $casts = [
        'api_key' => 'encrypted',
    ];
    
  3. Soft Deletes Enable soft deletes in the model:

    use Illuminate\Database\Eloquent\SoftDeletes;
    class SiteSettings extends Settings {
        use SoftDeletes;
        protected $dates = ['deleted_at'];
    }
    
  4. Observers Add logic before/after saves:

    SiteSettings::observe(SettingsObserver::class);
    
  5. Testing Mock settings in tests:

    SiteSettings::shouldReceive('get')->andReturn(['test' => 'value']);
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity