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

Schema Builder Laravel Package

cycle/schema-builder

Fluent PHP schema builder for Cycle ORM. Define tables, columns, indexes and relations in code, then generate/compile database schema changes for migrations and tooling. Helps keep your domain models and database structure in sync.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require cycle/schema-builder
    

    Add to composer.json under require-dev if only for migrations:

    "cycle/schema-builder": "^1.0"
    
  2. Basic Schema Definition Create a schema builder class (e.g., app/Schemas/UserSchema.php):

    use Cycle\Schema\Builder;
    use Cycle\Schema\Table;
    
    class UserSchema
    {
        public function build(Builder $builder): void
        {
            $builder->table('users', function (Table $table) {
                $table->uuid('id')->primary();
                $table->string('name')->notNull();
                $table->timestamp('created_at')->defaultNow();
            });
        }
    }
    
  3. First Use Case: Migration Register the schema in bootstrap/app.php:

    $app->make(\Cycle\Schema\Builder::class)->build(new UserSchema());
    

    Run migrations via Cycle ORM’s CLI:

    php artisan cycle:migrate
    

Implementation Patterns

Declarative Schema Workflows

  1. Modular Schema Definitions Split schemas by domain (e.g., UserSchema, PostSchema) and compose them in a root schema:

    $builder->schema(new UserSchema())->schema(new PostSchema());
    
  2. Reusable Schema Components Extract common patterns into traits or standalone builders:

    trait SoftDeletes
    {
        public function addSoftDeletes(Table $table): void
        {
            $table->timestamp('deleted_at')->nullable();
        }
    }
    
  3. Schema Versioning Use schema classes with versioned namespaces (e.g., v2/UserSchema) and conditionally apply them:

    if (app()->environment('production')) {
        $builder->schema(new UserSchemaV2());
    }
    

Integration with Cycle ORM

  • Entity Mapping Sync Regenerate entities after schema changes:
    php artisan cycle:generate
    
  • Schema Validation Use cycle:schema:validate to check for inconsistencies between schema and database:
    php artisan cycle:schema:validate
    

Advanced Patterns

  1. Dynamic Schema Generation Generate schemas from API specs (e.g., OpenAPI) or runtime data:

    $builder->table('dynamic_'.$request->type, function (Table $table) use ($request) {
        // ...
    });
    
  2. Schema Hooks Attach pre/post hooks to schema operations:

    $builder->onBuild(function (Builder $builder) {
        // Add indexes or triggers globally
    });
    

Gotchas and Tips

Common Pitfalls

  1. Schema Caching

    • Issue: Schema changes may not reflect in the database if cached.
    • Fix: Clear the schema cache after changes:
      php artisan cycle:schema:clear
      
    • Tip: Disable caching in config/cycle.php during development:
      'schema' => [
          'cache' => env('APP_ENV') !== 'local',
      ],
      
  2. Foreign Key Constraints

    • Issue: Adding a foreign key after the table exists may fail.
    • Fix: Use onUpdate('cascade') or onDelete('set null') explicitly:
      $table->foreign('user_id')->references('id')->on('users')->onDelete('set null');
      
  3. Case Sensitivity

    • Issue: Some databases (e.g., PostgreSQL) are case-sensitive for table/column names.
    • Fix: Use consistent naming conventions (e.g., snake_case) and quote identifiers:
      $table->column('`user_id`')->unsigned();
      

Debugging Tips

  • Schema Diff Compare current schema with the database:
    php artisan cycle:schema:diff
    
  • Verbose Output Enable verbose logging in config/cycle.php:
    'debug' => true,
    

Extension Points

  1. Custom Column Types Extend Cycle\Schema\Column for database-specific types:

    class JsonColumn extends Column
    {
        public function getType(): string
        {
            return 'jsonb';
        }
    }
    

    Use it in schemas:

    $table->column(new JsonColumn('metadata'));
    
  2. Schema Events Listen to schema build events via Laravel’s event system:

    SchemaBuilt::dispatch($builder);
    
  3. Database-Specific Quirks

    • MySQL: Use char(36) for UUIDs if not using a binary column.
    • SQLite: Disable foreign key checks during migrations:
      $builder->onBuild(function (Builder $builder) {
          $builder->execute('PRAGMA foreign_keys = OFF;');
      });
      
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.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
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