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 Info Laravel Package

spatie/laravel-model-info

Inspect Laravel Eloquent models to discover their file name, table name, attributes (name/type) and relations (name/type/related model). Also includes a ModelFinder to automatically locate all models in your application.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Introspection Tool: The package provides runtime reflection of Laravel model structures (attributes, relations, table names, etc.), making it ideal for schema-aware applications (e.g., admin panels, dynamic form builders, API documentation generators, or migration tools).
  • Non-Invasive: Operates purely via reflection/parsing (no database queries or model modifications), ensuring zero impact on existing logic.
  • Use Cases:
    • Dynamic UI Generation: Build forms or CRUD interfaces without hardcoding model metadata.
    • API Documentation: Auto-generate OpenAPI/Swagger specs or API contracts.
    • Validation/Testing: Verify model structures programmatically (e.g., CI/CD checks for schema drift).
    • Legacy System Analysis: Reverse-engineer undocumented models in large codebases.

Integration Feasibility

  • Laravel-Centric: Designed for Laravel’s Eloquent ORM; leverages Laravel’s service container and model conventions (e.g., App\Models\* namespace).
  • Zero Configuration: No database setup, migrations, or publisher scripts required. Install via Composer and use immediately.
  • Dependency Lightweight: Only requires PHP 8.1+ and Laravel 9+/10+ (as of 2026). No external services or heavy libraries.

Technical Risk

  • Reflection Limitations:
    • Dynamic Properties: May miss attributes/relations defined via append(), hidden(), or magic methods (e.g., getAttribute()).
    • Custom Accessors/Mutators: Won’t detect logic in getXAttribute()/setXAttribute() unless explicitly parsed (package uses get_defined_vars() + get_class_vars()).
    • Polymorphic Relations: May not resolve polymorphic targets (e.g., morphTo) without additional logic.
  • Performance:
    • Reflection is not free; heavy usage (e.g., iterating all models in a loop) could introduce latency. Cache results aggressively if used frequently.
    • Mitigation: Cache ModelInfo instances (e.g., via Laravel’s cache or a singleton service).
  • Edge Cases:
    • Abstract Models: May not handle abstract base models or traits correctly.
    • Proxy Models: Could misreport relations if using Laravel’s HasFactory or similar proxies.

Key Questions

  1. Scope of Usage:
    • Will this replace existing metadata management (e.g., manual annotations, XML/YAML configs)?
    • Is it for development-time (e.g., IDE tooling) or runtime (e.g., dynamic API generation)?
  2. Accuracy Requirements:
    • Are there critical use cases where missing a relation/attribute is unacceptable (e.g., security-sensitive fields)?
  3. Performance Budget:
    • How often will ModelInfo be queried? Can results be cached?
  4. Alternatives:
    • Could existing tools (e.g., Laravel Scout, custom reflection, or IDE plugins) suffice?
    • Is there a need for write-time metadata (e.g., updating docs when models change)?

Integration Approach

Stack Fit

  • Laravel Ecosystem: Seamless integration with Eloquent models, service container, and caching systems.
  • Complementary Packages:
    • Dynamic Forms: Pair with spatie/laravel-medialibrary or filamentphp/filament for UI generation.
    • API Tools: Integrate with darkaonline/l5-swagger or zircote/swagger-php for auto-docs.
    • Testing: Use with pestphp/pest or phpunit to assert model schemas.
  • Non-Laravel PHP: Limited utility outside Laravel (no ORM-specific features).

Migration Path

  1. Pilot Phase:
    • Start with a single high-value model (e.g., User) to validate accuracy and performance.
    • Replace one manual metadata source (e.g., a config file) with ModelInfo.
  2. Incremental Rollout:
    • Phase 1: Use for read-only operations (e.g., API docs, admin panels).
    • Phase 2: Extend to runtime logic (e.g., dynamic validation rules).
  3. Fallback Strategy:
    • Cache ModelInfo results to mitigate reflection overhead.
    • Provide a fallback() method in your wrapper to return cached/predefined data if reflection fails.

Compatibility

  • Laravel Versions: Tested on Laravel 9+/10+ (as of 2026). Verify compatibility with your version.
  • PHP Extensions: Requires no additional extensions (uses core reflection).
  • Model Customizations:
    • Traits: Works with traits, but may not merge metadata from multiple traits correctly (test thoroughly).
    • Macros: Ignores model macros (e.g., asJson()) unless they modify $fillable/$casts.

Sequencing

  1. Installation:
    composer require spatie/laravel-model-info
    
    Publish config if extending defaults (though none exist by default).
  2. Wrapper Layer (Recommended): Create a service class to handle caching and edge cases:
    class EnhancedModelInfo {
        public static function forModel(string $modelClass): ModelInfo {
            return cache()->remember("model_info.{$modelClass}", now()->addHours(1), fn() =>
                ModelInfo::forModel($modelClass)
            );
        }
    }
    
  3. Integration Points:
    • Service Providers: Bind EnhancedModelInfo to the container.
    • Middleware: Use to preload model metadata for API routes.
    • Commands: Generate docs or validate schemas on demand.

Operational Impact

Maintenance

  • Low Overhead:
    • No database migrations or schema changes.
    • Updates only require Composer updates (package is MIT-licensed and actively maintained).
  • Monitoring:
    • Track reflection performance in production (e.g., via Laravel Debugbar or Sentry).
    • Alert on ModelInfo failures (e.g., missing models, parsing errors).

Support

  • Troubleshooting:
    • Debug reflection issues with dd(ModelInfo::forModel(YourModel::class)->toArray()).
    • Common pitfalls: dynamic properties, custom accessors, or proxy models.
  • Documentation:
    • Extend the package’s README with your team’s use cases (e.g., "How we use this for API docs").
    • Create internal docs for edge cases (e.g., "Handling polymorphic relations").

Scaling

  • Performance:
    • Cache Aggressively: Store ModelInfo results in Redis/Memcached for >100ms response times.
    • Batch Processing: Avoid calling ModelInfo in loops (e.g., preload all models at app boot).
  • Horizontal Scaling:
    • Stateless design means no scaling issues; reflection is per-request.

Failure Modes

Failure Scenario Impact Mitigation
Reflection parsing fails Missing metadata for a model Fallback to cached/predefined data
Model namespace changes ModelInfo returns stale data Invalidate cache on model changes (e.g., via ModelEvent::saved)
PHP version incompatibility Package breaks Pin PHP version in composer.json
Dynamic properties ignored Incomplete attribute/relation lists Supplement with manual annotations

Ramp-Up

  • Onboarding:
    • Developers: 1-hour workshop to demonstrate use cases (e.g., building a dynamic form).
    • QA: Test with 3–5 critical models to validate accuracy.
  • Training:
    • Show how to extend ModelInfo for custom logic (e.g., filtering sensitive fields).
    • Document common anti-patterns (e.g., relying on reflection for critical logic).
  • Adoption Metrics:
    • Track usage in logs (e.g., ModelInfo::forModel() calls).
    • Measure reduction in manual metadata maintenance.
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport
twbs/bootstrap4