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

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/laravel-model-info
    

    No publisher required—just install and use.

  2. First Use Case: Inspect a model’s structure dynamically without manually reading its class or migrations:

    use Spatie\ModelInfo\ModelInfo;
    
    $modelInfo = ModelInfo::forModel(App\Models\Post::class);
    dd($modelInfo->attributes, $modelInfo->relations);
    
  3. Key Starting Points:

    • ModelInfo::forModel(): Core entry point for any model.
    • $modelInfo->fileName: Locate the model’s file path (useful for IDE navigation or refactoring).
    • $modelInfo->tableName: Verify table names without opening migrations.
    • $modelInfo->attributes/$modelInfo->relations: Iterate over collections of Attribute/Relation objects.

Implementation Patterns

Common Workflows

  1. Dynamic Form/Validation Generation:

    $fields = collect($modelInfo->attributes)
        ->map(fn($attr) => [
            'name' => $attr->name,
            'type' => $attr->type,
            'label' => ucfirst(str_replace('_', ' ', $attr->name)),
        ]);
    

    Use case: Auto-generate CRUD forms or API schemas (e.g., OpenAPI) from models.

  2. Relation-Aware Queries:

    $relatedModels = $modelInfo->relations
        ->pluck('relatedModel')
        ->unique()
        ->map(fn($class) => new $class);
    

    Use case: Preload related models or validate foreign keys.

  3. Model Documentation:

    $doc = "## {$modelInfo->className}\n";
    $doc .= "**Table**: {$modelInfo->tableName}\n";
    $doc .= "**Attributes**:\n";
    $doc .= $modelInfo->attributes->map(fn($attr) => "- `$attr->name`: `$attr->type`")
        ->implode("\n");
    

    Use case: Auto-generate Swagger docs or README snippets.

  4. Migration Helpers:

    $columns = $modelInfo->attributes->mapWithKeys(fn($attr) => [
        $attr->name => "{$attr->type}" . ($attr->nullable ? '->nullable()' : ''),
    ]);
    

    Use case: Reverse-engineer migrations or validate existing DB schemas.

  5. Testing Utilities:

    public function testModelStructure()
    {
        $modelInfo = ModelInfo::forModel(Post::class);
        $this->assertEquals(['title', 'body'], $modelInfo->attributes->pluck('name'));
    }
    

    Use case: Assert model structure in PHPUnit tests.


Integration Tips

  • Caching: Cache ModelInfo instances for performance-critical paths:
    $cacheKey = "model_info:{$modelClass}";
    $modelInfo = Cache::remember($cacheKey, now()->addHours(1), fn() =>
        ModelInfo::forModel($modelClass)
    );
    
  • Laravel Scout: Use modelInfo->attributes to dynamically index searchable fields.
  • Laravel Nova: Extend Nova tooling to reflect model changes in real-time.
  • API Contracts: Generate JSON:API or GraphQL schemas dynamically.

Gotchas and Tips

Pitfalls

  1. Caching Quirks:

    • ModelInfo caches results per model class. Clear cache if models change:
      php artisan cache:clear
      
    • Workaround: Use ModelInfo::forModel($class, true) to force refresh.
  2. Relation Resolution:

    • Nested relations (e.g., hasManyThrough) may not resolve fully. Use ->relatedModel cautiously for direct relations only.
    • Tip: Combine with getMorphClass() for polymorphic relations.
  3. Attribute Type Inference:

    • Custom accessors/mutators may mislead $attr->type. Use $attr->getType() for raw DB types.
    • Example:
      $attr->type; // Might return 'string' even if the DB column is `text`.
      
  4. Model Events:

    • Changes to $fillable, $casts, or relations aren’t reflected in real-time. Re-fetch ModelInfo after updates.
  5. Global Scope Interference:

    • Scopes (e.g., globalScope) don’t affect ModelInfo. Use Model::query()->get() for runtime data.

Debugging Tips

  • Verify Model Paths:

    dd(ModelInfo::forModel(Post::class)->fileName);
    

    Use case: Debug if the package can’t locate a model (e.g., namespaced models).

  • Inspect Relation Types:

    $relation = $modelInfo->relations->first();
    dd($relation->type, $relation->relatedModel, $relation->foreignKey);
    

    Use case: Troubleshoot mismatched relation configurations.

  • Check for Custom Logic:

    • Override Spatie\ModelInfo\Attribute or Relation classes if default behavior is insufficient.

Extension Points

  1. Custom Attribute Types:

    // app/Providers/ModelInfoServiceProvider.php
    use Spatie\ModelInfo\Attribute;
    
    public function boot()
    {
        Attribute::macro('isEncrypted', function() {
            return $this->type === 'string' && str_contains($this->name, 'encrypted_');
        });
    }
    
  2. Relation Metadata:

    // Extend Relation class to add custom properties
    $modelInfo->relations->each(function($relation) {
        $relation->setAttribute('isRequired', $relation->type === 'BelongsTo');
    });
    
  3. Event Listeners:

    • Listen to ModelInfoGenerated events to log or transform model metadata:
      ModelInfo::macro('generate', function($class) {
          event(new ModelGenerated($class, ModelInfo::forModel($class)));
      });
      
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
milesj/emojibase
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