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

Eloquence Laravel Package

kirkbushell/eloquence

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require kirkbushell/eloquence
    

    No additional configuration is required for Laravel 5.5+ (automatically discoverable).

  2. First Use Case: Enable camelCase attributes for JSON/API consistency by adding HasCamelAttributes to your model:

    use Eloquence\Behaviours\Attributes\HasCamelAttributes;
    
    class User extends Model {
        use HasCamelAttributes;
    }
    

    Now, User::find(1)->toArray() returns ['firstName' => 'John'] instead of ['first_name' => 'John'].

  3. Key Entry Points:

    • README for trait list.
    • Tests for real-world examples.

Implementation Patterns

Core Workflows

  1. Attribute Transformation:

    • CamelCase: Use HasCamelAttributes for API responses or consistency with frontend code.
    • SnakeCase: Use HasSnakeAttributes for database storage (default behavior).
    • Custom: Extend AttributeTransformer for bespoke logic (e.g., HasKebabAttributes).
    // API Model (camelCase)
    class ApiUser extends Model {
        use HasCamelAttributes;
        protected $casts = ['created_at' => 'datetime:Y-m-d'];
    }
    
    // Database Model (snake_case)
    class User extends Model {
        use HasSnakeAttributes;
    }
    
  2. Readonly Models:

    • Protect sensitive data (e.g., logs, audit trails) with HasReadOnly:
      class AuditLog extends Model {
          use HasReadOnly;
          protected $fillable = []; // Explicitly block mass assignment
      }
      
    • Workaround: Use forceFill() or forceSave() for edge cases (documented in the package).
  3. Data Aggregation:

    • Use HasAggregates to preload computed fields (e.g., total_orders):
      class Customer extends Model {
          use HasAggregates;
          protected $aggregates = [
              'total_orders' => ['orders', 'count']
          ];
      }
      
    • Access via $customer->total_orders (lazy-loaded).
  4. Query Logging:

    • Enable via config (eloquence.log_queries = true) to debug slow queries or validate SQL.

Integration Tips

  • API Layer: Combine HasCamelAttributes with Laravel’s Resource classes for consistent JSON output.
  • Testing: Use HasReadOnly for immutable test data (e.g., fixtures).
  • Migrations: Leverage HasTimestamps or HasUuids traits to standardize schema definitions.

Gotchas and Tips

Pitfalls

  1. Readonly Models:

    • Gotcha: save(), update(), or fill() will throw ReadonlyException. Fix: Use forceFill(['key' => 'value'])->save() or new static($attributes).
    • Tip: Override isFillable() to allow specific fields:
      public function isFillable(array $attributes) {
          return in_array('metadata', $attributes);
      }
      
  2. Attribute Conflicts:

    • Gotcha: Mixing HasCamelAttributes with HasSnakeAttributes causes silent attribute mismatches. Fix: Stick to one transformer per model hierarchy.
  3. Aggregates:

    • Gotcha: Circular dependencies (e.g., user.orders.user) cause infinite loops. Fix: Use with() to eager-load relationships before accessing aggregates.
  4. Query Logging:

    • Gotcha: Logs may bloat in production. Fix: Disable via config or use Laravel’s debugbar for conditional logging.

Debugging

  • Attribute Issues: Use dd($model->getAttributes()) to inspect raw vs. transformed values.
  • Readonly Errors: Check config('eloquence.readonly') for global overrides.
  • Aggregate Failures: Verify relationship names in $aggregates match the model’s belongsTo/hasMany.

Extension Points

  1. Custom Transformers:

    • Extend AttributeTransformer to add new cases (e.g., HasPascalAttributes):
      class PascalTransformer extends AttributeTransformer {
          public function transform($value, $key) {
              return ucfirst(camel_case($key));
          }
      }
      
  2. Readonly Exceptions:

    • Override throwReadonlyException() to customize error messages or redirect users.
  3. Aggregate Logic:

    • Extend Aggregate class to support custom SQL or non-relational calculations.

Config Quirks

  • Global Readonly: Set eloquence.readonly to true in config/eloquence.php to enforce readonly on all models.
  • Query Logging: Logs are stored in storage/logs/eloquent.log by default; adjust via eloquence.log_file.
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.
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
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle