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

laracraft-tech/laravel-dynamic-model

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require laracraft-tech/laravel-dynamic-model
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="LaracraftTech\DynamicModel\DynamicModelServiceProvider"
    
  2. Basic Usage: Define a model extending DynamicModel:

    use LaracraftTech\DynamicModel\DynamicModel;
    
    class MultiTableModel extends DynamicModel
    {
        protected $table = null; // Will be set dynamically
    }
    
  3. First Use Case: Dynamically switch tables at runtime:

    $model = new MultiTableModel();
    $model->setTable('users'); // Switch to 'users' table
    $user = $model->find(1); // Query 'users' table
    

Where to Look First

  • Config: config/dynamic-model.php (if published) for default behaviors.
  • Documentation: Check the README.md for table-switching logic and query customization.
  • Tests: tests/ directory for edge cases and examples.

Implementation Patterns

Core Workflows

  1. Dynamic Table Switching:

    // Switch table dynamically
    $model->setTable('products');
    $product = $model->find(1);
    
    // Or via constructor
    $model = new MultiTableModel(['table' => 'orders']);
    
  2. Multi-Database Support:

    $model->setConnection('mysql_slave');
    $model->setTable('analytics');
    $data = $model->all();
    
  3. Query Customization: Override getTable() or getConnection():

    class CustomModel extends DynamicModel
    {
        public function getTable()
        {
            return request()->input('table') ?? parent::getTable();
        }
    }
    

Integration Tips

  • Polymorphic Relationships: Use morphTo with dynamic models for flexible relationships:

    class Post extends Model {
        public function owner()
        {
            return $this->morphTo()->type('user')->model(MultiTableModel::class);
        }
    }
    
  • API Endpoints: Dynamically resolve tables based on route parameters:

    Route::get('/data/{table}', function ($table) {
        $model = new MultiTableModel();
        $model->setTable($table);
        return $model->all();
    });
    
  • Caching: Cache table configurations if tables are static:

    $model->setTable('cached_table');
    $model->setConnection('cached_db');
    

Gotchas and Tips

Pitfalls

  1. Table Validation:

    • Gotcha: No built-in validation for table existence. Always validate tables manually:
      if (!Schema::hasTable($model->getTable())) {
          throw new \InvalidArgumentException("Table {$model->getTable()} does not exist.");
      }
      
    • Tip: Use Schema::hasTable() or DB::select("SHOW TABLES LIKE '$table'") for MySQL.
  2. Query Builder Conflicts:

    • Gotcha: Dynamic models may conflict with Laravel’s query caching or global scopes if not handled:
      // Disable global scopes temporarily
      $model->withoutGlobalScopes(function () use ($model) {
          return $model->where('active', 1)->get();
      });
      
  3. Mass Assignment:

    • Gotcha: Dynamic models inherit Laravel’s mass assignment rules. Ensure $fillable is defined per table if needed:
      protected $fillable = ['name', 'email']; // Default
      public function setTable($table)
      {
          if ($table === 'admins') {
              $this->fillable = ['username', 'role'];
          }
          return parent::setTable($table);
      }
      

Debugging

  • Log Table Switches: Add a trait to log table changes:

    trait LogsTableSwitches
    {
        public function setTable($table)
        {
            \Log::debug("Switched table to: {$table}", ['model' => static::class]);
            return parent::setTable($table);
        }
    }
    
  • Query Logging: Enable Laravel’s query logging:

    DB::enableQueryLog();
    $model->find(1);
    \Log::debug(DB::getQueryLog());
    

Extension Points

  1. Custom Table Resolution: Override resolveTable() to implement logic like:

    public function resolveTable($table = null)
    {
        return $table ?? config("dynamic-model.default_table");
    }
    
  2. Event Hooks: Listen for model.setTable events (if supported in future versions) or use traits:

    trait TableSwitchListener
    {
        public function setTable($table)
        {
            event(new TableSwitched($this, $table));
            return parent::setTable($table);
        }
    }
    
  3. Soft Deletes: Handle soft deletes per table:

    public function getDeletedAtColumn()
    {
        return $this->getTable() === 'archived_users' ? 'deleted_at' : null;
    }
    

Config Quirks

  • Default Table: Set in config/dynamic-model.php:
    'default_table' => 'default',
    'default_connection' => null,
    
  • Multi-Database: Ensure your .env has multiple database connections configured:
    DB_CONNECTION_mysql_slave=mysql
    DB_HOST_mysql_slave=slave.example.com
    
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.
milito/query-filter
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