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 Model Settings Laravel Package

lukasss93/laravel-model-settings

Add per-model settings to Eloquent with defaults, validation rules, and optional config publishing. Store and retrieve settings directly on your models, initialize settings on creation, and keep your app flexible with PHP 8+ and Laravel 8+ support.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Strengths:

    • Flexible Storage Backends: Supports JSON field, dedicated table, or Redis for settings storage, aligning with Laravel’s modularity and scalability needs. This allows TPMs to choose based on read/write patterns (e.g., Redis for high-frequency access, table for complex queries).
    • Validation Integration: Native Laravel validation rules for settings (settingsRules()) reduce boilerplate and enforce consistency, critical for compliance-heavy or data-sensitive applications (e.g., SaaS platforms).
    • Laravel 11+ Compatibility: Actively maintained with clear upgrade paths, mitigating technical debt for teams adopting newer Laravel versions.
    • Default/Initialization Logic: Methods like defaultSettings() and initSettings simplify onboarding for new models, reducing manual setup in migrations or seeders.
  • Weaknesses:

    • Limited Query Capabilities: Settings stored as JSON/Redis lack native SQL querying (e.g., filtering users by settings->language = 'en'). Requires application-level parsing or full-table scans for complex queries.
    • Schema Rigidity: Field/table-based storage may not adapt to evolving schemas without migrations (e.g., adding nested settings later).
    • No Built-in Caching Layer: While Redis is an option, the package doesn’t abstract caching strategies (e.g., tag-based invalidation for settings changes).

Integration Feasibility

  • Laravel Ecosystem Fit:

    • Seamless Trait Integration: Minimal boilerplate (use HasSettingsField/Table/Redis) with zero configuration for basic use cases. Ideal for greenfield projects or incremental adoption.
    • Artisan Commands: model-settings:model-settings-field/table automate schema setup, reducing manual migration errors.
    • PSR Compliance: Adheres to PSR-1/2/4/12, ensuring compatibility with Laravel’s dependency injection and service container.
  • Migration Path:

    • Backward Compatibility: Supports Laravel 8–11, but breaking changes (e.g., defaultSettings method conversion) may require refactoring in legacy codebases.
    • Hybrid Adoption: Can coexist with existing config systems (e.g., .env or config/) by scoping settings to specific models (e.g., User::settings()->get('theme') vs. config('app.theme')).

Technical Risk

  • Performance:

    • JSON Field: Risk of bloated rows if settings grow large (e.g., >1KB). Monitor with DB::select("SELECT AVG(LENGTH(settings)) FROM users").
    • Table Storage: Joins for settings access may impact queries. Mitigate with indexing (e.g., model_id, setting_key composite index).
    • Redis: Network latency for distributed setups; test with redis-cli --latency before production.
  • Data Integrity:

    • Validation Gaps: Rules apply only to set()/apply(), not direct DB updates (e.g., via raw SQL). Use model observers or gates to enforce consistency.
    • Concurrency: No built-in locking for apply()/setMultiple. For critical settings (e.g., payment thresholds), implement optimistic locking ($model->settings()->set('threshold', $newValue, ['lock_for' => 5])).
  • Testing:

    • Edge Cases: Limited test coverage for nested arrays or circular references in settings. Add PestPHP tests for:
      test('nested_settings_preserve_structure')->assertEquals(
          ['a' => ['b' => 1]],
          $model->settings()->set('a.b', 1)->get()
      );
      
    • Migration Safety: Test rollback scenarios for model-settings:model-settings-field (e.g., php artisan migrate:rollback).

Key Questions for TPM

  1. Storage Tradeoffs:

    • Field vs. Table vs. Redis: Benchmark with your expected CRUD patterns (e.g., 90% reads vs. 10% writes).
    • Example: For a Product model with 1M rows, test:
      ab -n 10000 -c 100 "GET /api/products/1/settings"  # Field vs. Table latency
      
  2. Schema Evolution:

    • How will you handle breaking changes to settings (e.g., renaming user.theme to user.preferences.theme)? Options:
      • Migration: Add a settings_migration_version field to track updates.
      • Fallback: Use settings()->get('user.theme', $settings->get('user.preferences.theme')).
  3. Access Control:

    • Are settings model-scoped (e.g., User settings) or global? If global, consider a Settings model with setting_key/setting_value columns.
  4. Observability:

    • How will you audit setting changes? Options:
      • Logs: Wrap set() in a logger (e.g., event(new SettingUpdated($model, $key, $oldValue, $newValue))).
      • Database: Add updated_at to the settings table/field.
  5. Team Adoption:

    • Developer Experience: Will teams prefer user->settings()->set('key', 'value') or a fluent builder (e.g., Settings::for($user)->set('key', 'value'))?
    • Documentation: The README lacks examples for nested validation or Redis TTLs. Plan for internal docs or a Settings facade wrapper.

Integration Approach

Stack Fit

  • Laravel Core:

    • Service Provider: Registers ModelSettingsServiceProvider automatically, integrating with Laravel’s service container.
    • Query Builder: Extends Eloquent models without monkeypatching core classes, preserving upgradeability.
    • Validation: Leverages Laravel’s validator, reducing dependency on third-party libraries.
  • Database:

    • Field Storage: Requires JSON column (PostgreSQL, MySQL 5.7+). For SQLite, use json type or serialize manually.
    • Table Storage: Creates a model_settings table with model_type, model_id, setting_key, setting_value columns. Customize via php artisan vendor:publish --tag="model-settings-config".
    • Redis: Uses Redis::hash for O(1) access. Configure in .env:
      MODEL_SETTINGS_REDIS_CONNECTION=cache
      MODEL_SETTINGS_REDIS_KEY_PREFIX=settings_
      
  • Caching:

    • Optional: Cache settings in-memory (e.g., Cache::remember) for high-read workloads. Example:
      public function getSettings()
      {
          return Cache::remember(
              "settings_{$this->id}",
              now()->addHours(1),
              fn() => $this->settings()->get()
          );
      }
      

Migration Path

  1. Assessment Phase:

    • Audit existing settings (e.g., .env, config/, or custom tables) to identify candidates for migration.
    • Example: Replace config('app.feature_flags') with App\Settings::get('feature_flags').
  2. Pilot Model:

    • Start with a non-critical model (e.g., NewsletterSubscription) to test:
      • Field vs. table performance.
      • Validation rules for edge cases (e.g., settingsRules(['max_subscribers' => 'integer|max:1000'])).
    • Use HasSettingsField for simplicity, switch to HasSettingsTable if settings exceed 1KB.
  3. Incremental Rollout:

    • Phase 1: Migrate read-heavy settings (e.g., user preferences).
    • Phase 2: Replace global configs with model-scoped settings (e.g., Product::settings()->get('price_currency')).
    • Phase 3: Deprecate legacy config files with middleware:
      // app/Http/Middleware/DeprecateLegacyConfigs.php
      public function handle($request, Closure $next)
      {
          if (config('app.legacy_configs_enabled')) {
              Log::warning('Legacy config accessed', ['config' => config('app.theme')]);
          }
          return $next($request);
      }
      
  4. Schema Changes:

    • For HasSettingsField:
      php artisan model-settings:model-settings-field User
      php artisan migrate
      
    • For HasSettingsTable:
      php artisan model-settings:model-settings-table User
      php artisan migrate
      

Compatibility

  • Laravel Versions: Tested on 8–11. For Laravel 12+, check for breaking changes in Illuminate\Database\Eloquent\Model.
  • PHP Extensions: Requires json and pdo extensions. For Redis, install predis/predis.
  • Third-Party Conflicts:
    • Package Conflicts: None reported. Use composer why lukasss93/laravel-model-settings to check dependencies.
    • Model Conflicts: Avoid naming collisions with existing traits (e.g., HasSettings
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