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

onelearningcommunity/laravel-model-explorer

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require onelearningcommunity/laravel-model-explorer
    

    No additional configuration or publishing is required.

  2. Access the Tool:

    • Run your Laravel application locally.
    • Visit /model-explorer in your browser (e.g., http://localhost:8000/model-explorer).
  3. First Use Case:

    • Explore Models: Navigate to the "Model list" tab to see all Eloquent models in your application. Click on any model to view its:
      • Database columns (with types and nullable status).
      • Casts, fillable, guarded, and hidden attributes.
      • Relationships (with foreign key details and relationship types).
      • Scopes, traits, and accessors (with code snippets).
    • Inspect Records: Use the "Record lookup" tab to search for records by primary key or unique fields. Expand relations to inspect nested data dynamically.

Implementation Patterns

Core Workflows

  1. Debugging Relationships:

    • Use the "Model detail" view to visualize complex relationships (e.g., polymorphic, many-to-many) and their foreign keys. This replaces manual dd() or toArray() calls during development.
    • Example: Debugging a belongsToMany relationship:
      • Open the pivot table model in the explorer to see its structure.
      • Use "Record lookup" to fetch a record and expand the relationship to verify data.
  2. Onboarding New Developers:

    • Share the /model-explorer URL during code reviews or pair programming to quickly familiarize team members with the schema and model logic.
    • Example: Point to a model’s "Scopes" section to explain how filtering works without diving into the codebase.
  3. Dynamic Data Exploration:

    • Use "Record lookup" to test live data without writing queries. For example:
      • Find a user by email and expand their posts relationship to verify data integrity.
      • Check computed attributes (accessors) by expanding the record’s attributes section.
  4. Schema Documentation:

    • Treat the tool as a living schema documentation system. Bookmark the /model-explorer route in your IDE or browser for quick reference.
    • Example: Before writing a migration, check the "Model detail" view to confirm column types or existing constraints.
  5. Integration with Testing:

    • Use the tool to validate test data setup. For example:
      • After seeding, use "Record lookup" to verify that relationships are correctly populated.
      • Cross-check computed attributes (e.g., full_name accessors) against expected values.

Advanced Patterns

  1. Customizing the Explorer:

    • Extend the tool by publishing its views (though the package claims "zero setup," you can override views via vendor:publish --provider="OneLearningCommunity\ModelExplorer\ModelExplorerServiceProvider" if needed).
    • Example: Add custom tabs or filters by extending the ModelExplorerController.
  2. API-Driven Exploration:

    • The package exposes routes for programmatic access (e.g., /api/models, /api/models/{model}/records). Use these in custom admin panels or CLI tools.
    • Example: Build a CLI command to fetch and log all records of a model:
      $records = Http::get("http://localhost:8000/api/models/{$modelClass}/records");
      
  3. Performance Profiling:

    • Use the explorer to identify models with heavy relationships or accessors that might impact performance. For example:
      • Look for models with many hasManyThrough or morphTo relationships.
      • Check accessors that might trigger expensive logic.
  4. Seeding Validation:

    • After running a seeder, use the explorer to verify that:
      • Required fields are populated.
      • Relationships are correctly linked.
      • Computed attributes match expectations.

Gotchas and Tips

Pitfalls

  1. Excluded Models:

    • The explorer skips models in the app/Models namespace by default. To include them, add the namespace to the discoverModels config:
      'namespaces' => [
          'App\Models',
          'App\\Other\\Namespace', // Add custom namespaces here
      ],
      
    • Debug Tip: If a model isn’t appearing, check the config/model-explorer.php file for excluded namespaces or models.
  2. Performance with Large Datasets:

    • The "Record lookup" feature loads records eagerly by default. For models with large datasets or complex relationships, this may cause timeouts or high memory usage.
    • Workaround: Use the limit query parameter (e.g., /model-explorer/records?model=App\Models\User&limit=10) or filter by a unique field (e.g., ?field=email&value=test@example.com).
  3. Caching Issues:

    • The explorer caches model metadata to improve performance. Clear the cache if changes to models (e.g., new relationships or accessors) aren’t reflected:
      php artisan cache:clear
      php artisan config:clear
      
  4. Polymorphic Relationships:

    • Polymorphic relationships (e.g., morphTo) may not display foreign key details clearly in the UI. Manually verify these in the database or by inspecting the raw attributes of a record.
  5. Hidden or Guarded Attributes:

    • Attributes marked as hidden or guarded in the model may not appear in the "Record lookup" view. Use the "Model detail" tab to confirm which attributes are excluded.
  6. Localization or Translation Issues:

    • If your models use localization (e.g., translatable package), the explorer may not display translated attributes dynamically. Stick to base attributes or use the raw data view.

Debugging Tips

  1. Check the Logs:

    • Enable debug mode (APP_DEBUG=true) to see any errors or warnings in the Laravel log (storage/logs/laravel.log). Common issues include:
      • Missing foreign keys in relationships.
      • Invalid model configurations.
  2. Inspect Raw Data:

    • Use the "Raw attributes" toggle in the "Record lookup" view to see unprocessed data, including hidden or computed fields. This is useful for debugging accessors or mutators.
  3. Verify Relationship Types:

    • If a relationship isn’t displaying correctly (e.g., missing foreign key), check the model’s relationship definition. The explorer highlights mismatches with warnings.
  4. Test with a Fresh Instance:

    • If the explorer behaves unexpectedly, test it in a fresh Laravel installation to rule out conflicts with other packages.

Extension Points

  1. Custom Filters:

    • Override the ModelExplorerController to add custom filters or actions. For example, add a "Soft Deletes" toggle to the record lookup:
      // app/Http/Controllers/ModelExplorerController.php
      public function records(Request $request, string $model)
      {
          $query = ModelExplorer::query($model);
          if ($request->has('with_deleted')) {
              $query->withDeleted();
          }
          return $query->get();
      }
      
  2. Add Custom Tabs:

    • Extend the ModelExplorerServiceProvider to register additional tabs or views. For example, add a "Model Events" tab to display registered listeners:
      // app/Providers/ModelExplorerServiceProvider.php
      public function boot()
      {
          ModelExplorer::extend(function ($explorer) {
              $explorer->addTab('events', function ($model) {
                  return view('model-explorer::tabs.events', ['model' => $model]);
              });
          });
      }
      
  3. Modify Record Display:

    • Override the record partial view (resources/views/vendor/model-explorer/partials/record.blade.php) to customize how records are rendered. For example, add syntax highlighting to accessor snippets.
  4. API Extensions:

    • Extend the /api/models endpoint to include custom metadata. For example, add a hasSoftDeletes field:
      // app/Http/Controllers/ModelExplorerController.php
      public function apiModels()
      {
          return ModelExplorer::all()->map(function ($model) {
              return array_merge($model->toArray(), [
                  'has_soft_deletes' => in_array(\Illuminate\Database\Eloquent\SoftDeletes::class, class_uses_recursive($model->getModel())),
              ]);
          });
      }
      
  5. Environment-Specific Configuration:

    • Use environment-specific config to disable the explorer in production or staging:
      // config/model-explorer.php
      'enabled' => env('MODEL_EXPLORER_ENABLED', false),
      
    • Then set MODEL_EXPLORER_ENABLED=true in your .env for local development.
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.
apiboxsym/user-bundle
apiboxsym/health-check-bundle
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