egyjs / dbml-to-laravel
Generate Laravel Eloquent models and migrations from DBML (dbdiagram.io) schema files, and incrementally sync schema changes into new migrations.
Package info
github.com/egyjs/dbml-to-laravel
Language:JavaScript
pkg:composer/egyjs/dbml-to-laravel
Fund package maintenance!
Requires
- php: ^8.2
- illuminate/contracts: ^8.0||^9.0||^10.0||^11.0||^12.0||^13.0
- illuminate/support: ^8.0||^9.0||^10.0||^11.0||^12.0||^13.0
- spatie/laravel-package-tools: ^1.16
- symfony/process: ^5.4|^6.0|^7.0|^8.0
Requires (Dev)
- larastan/larastan: ^2.9||^3.0
- laravel/pint: ^1.14
- nunomaduro/collision: ^8.1.1||^7.10.0||^6.0||^5.0
- orchestra/testbench: ^10.0.0||^9.0.0||^8.22.0||^7.0||^6.0
- pestphp/pest: ^3.0||^2.0||^1.0
- pestphp/pest-plugin-arch: ^3.0||^2.0||^1.0
- pestphp/pest-plugin-laravel: ^3.0||^2.0||^1.0
- phpstan/extension-installer: ^1.3||^2.0
- phpstan/phpstan-deprecation-rules: ^1.1||^2.0
- phpstan/phpstan-phpunit: ^1.3||^2.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
- dev-main
- v2.2.00
- v2.1.01
- v2.1.00
- v2.0.00
- 1.0.03
- 1.0.02
- 1.0.01
- 1.0.0
- dev-release/v2.2.00
- dev-fix/pk-nullable-and-cleanup
- dev-chore/lint-config
- dev-feat/ai-agent-boost-and-llms-txt
- dev-feat/docs-contributor-guides
- dev-copilot/fix-bigint-unsigned-issue
- dev-copilot/fix-dbml-parser-issue
- dev-codex/refactor-code-to-use-@dbml/core
- dev-community-updates
- dev-feature/update-github-workflow
- dev-feature/dbml-generator-enhancements
- dev-support-laravel-12
This package is auto-updated.
Last update: 2026-11-09 22:23:27 UTC
README
Generate Laravel Eloquent models and migration files directly from your DBML (Database Markup Language) diagrams, accelerating Laravel development and streamlining your schema-to-code workflow.
📰 Featured on Laravel News — the official community blog for Laravel developers!
⚡ Quick Start
composer require egyjs/dbml-to-laravel --dev php artisan dbml:generate database/schema.dbml # first run: models + migrations + snapshot php artisan dbml:sync database/schema.dbml --force # after each DBML edit: incremental migrations
🎯 When to Use This Package
Use egyjs/dbml-to-laravel when you want to:
- Turn a DBML schema or dbdiagram.io diagram into Laravel code — Eloquent models and migrations in one command.
- Keep the database schema in one declarative file (
database/schema.dbml) and generate migrations from changes, instead of hand-writingphp artisan make:migrationfiles. - Scaffold a new Laravel app's data layer quickly — fillable, casts,
belongsTo/hasManyrelations, foreign keys, indexes and enums. - Let AI coding agents change the schema safely — agents edit one DBML file and run
dbml:sync; see Using with AI Coding Agents.
It is not a tool for reverse-engineering an existing database into DBML, and it does not generate controllers, factories or seeders.
🚀 Motivation
Tired of manually writing Laravel Eloquent models and migration files from your database diagrams? This package automates the process, letting you focus on building features rather than repetitive boilerplate code. Say goodbye to manual schema-to-code conversion and embrace a faster, more efficient Laravel development workflow.
✨ Features
- DBML to Eloquent Models: Generates models with
$fillable,$casts, a$tableproperty when the table name is non-conventional, and relationship methods. - Relationships:
belongsToon the referencing model andhasManyon the referenced model, built from DBMLref/Ref:definitions. - DBML to Migrations: Column types, nullability, defaults,
unique, primary keys, auto-increment, enums, single and composite indexes, and foreign keys (onDelete/onUpdateforcascade,restrict,set null). - Casts:
boolean,array(json/jsonb),datetime,date,floatanddecimal:N, derived from DBML column types. - Incremental Sync:
dbml:syncdiffs the DBML file against a snapshot and generates create/alter/drop migrations, then patches models only inside@dbml-syncmarkers. - Customizable Stubs: Publish and edit the model and migration stubs to match your coding style.
Current Limitations
- Only many-to-one / one-to-many refs (
>and<) are used. One-to-one (-) and many-to-many (<>) refs are ignored — no foreign key,hasOne, pivot table orbelongsToManyis generated for them. $hidden, factories and seeders are not generated.- Columns without
not nullin DBML are generated as->nullable().
📦 Installation
To get started with the DBML to Laravel Eloquent Generator, follow these simple steps:
- Require the package via Composer:
composer require egyjs/dbml-to-laravel --dev
- Publish the customizable stubs (optional, but recommended):
php artisan vendor:publish --tag=dbml-to-laravel-stubs
This command will publish the stub files to stubs/dbml-to-laravel/, allowing you to customize the generated code.
Requirements
- Laravel 8.x+
- PHP 8.2+
- Node.js 18+ runtime (the DBML parser is pre-bundled, so you never need to run
npm installin your project)
💡 Usage
Once installed, you can generate your Laravel models and migrations from a DBML file using the dbml:generate Artisan command. (generate:dbml also works as a legacy alias.)
- Create your DBML schema file (e.g., database/schema.dbml).
Example database/schema.dbml:
Table users {
id int [pk, increment]
name varchar
email varchar [unique]
password varchar
created_at datetime
updated_at datetime
}
Table posts {
id int [pk, increment]
user_id int [ref: > users.id]
title varchar
content text
created_at datetime
updated_at datetime
}
Declare each relationship once — either inline ([ref: > users.id]) or as a top-level Ref: line, not both.
- Run the Artisan command:
php artisan dbml:generate database/schema.dbml
Replace database/schema.dbml with the actual path to your DBML file.
Expected Output
After running the command, the package will generate:
- Eloquent Models: In your
app/Modelsdirectory (e.g.,app/Models/User.php). - Migration Files: In your
database/migrationsdirectory (e.g.,2023_01_01_000000_create_posts_table.php).
Example Generated app/Models/Post.php (actual output for the schema above):
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Post extends Model { use HasFactory; // @dbml-sync:table-property // @enddbml-sync:table-property // @dbml-sync:fillable protected $fillable = [ 'user_id', 'title', 'content' ]; // @enddbml-sync:fillable // @dbml-sync:casts protected $casts = [ 'created_at' => 'datetime', 'updated_at' => 'datetime' ]; // @enddbml-sync:casts // @dbml-sync:relations public function user() { return $this->belongsTo(User::class, 'user_id', 'id'); } // @enddbml-sync:relations }
app/Models/User.php gets the inverse posts() → hasMany(Post::class, 'user_id', 'id') relation.
Example Generated database/migrations/2026_01_01_000001_create_posts_table.php:
Schema::create('posts', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->nullable(); $table->foreign('user_id')->references('id')->on('users'); $table->string('title', 255)->nullable(); $table->text('content')->nullable(); $table->timestamp('created_at')->nullable(); $table->timestamp('updated_at')->nullable(); });
Add not null to DBML columns that must be required (e.g. title varchar [not null]).
Incremental Sync
After your initial generate:dbml, you can iterate on your DBML schema and generate only the changes:
php artisan dbml:sync database/schema.dbml
This command:
- Reads the snapshot
.dbml-sync.jsonthatdbml:generatewrites next to your DBML file (e.g.database/.dbml-sync.json— commit it) - Compares it against the current DBML file
- Generates alter migrations for added/modified/dropped columns, indexes, and foreign keys
- Generates create migrations for new tables and drop migrations for removed tables
- Patches existing Eloquent models within
@dbml-syncmarkers (fillable, casts, relations, table property)
Use --force to skip confirmation prompts:
php artisan dbml:sync database/schema.dbml --force
Workflow example:
# Initial generation — creates models, migrations, and snapshot php artisan dbml:generate database/schema.dbml # ... edit schema.dbml (add columns, new tables, etc.) # Incremental sync — only the changes php artisan dbml:sync database/schema.dbml
Model markers. Generated models include @dbml-sync markers that the patcher targets:
class User extends Model { // @dbml-sync:fillable protected $fillable = ['name', 'email']; // @enddbml-sync:fillable // @dbml-sync:casts protected $casts = ['email_verified_at' => 'datetime']; // @enddbml-sync:casts // @dbml-sync:relations public function posts() { return $this->hasMany(Post::class); } // @enddbml-sync:relations }
Code outside these markers is never touched by dbml:sync.
🤖 Using with AI Coding Agents
This package is built to be driven by AI coding agents (Claude Code, Cursor, Codex, Copilot, etc.): the agent edits one declarative file instead of hand-writing migrations, and the generator produces deterministic Laravel code.
- Laravel Boost integration: the package ships Boost guidelines and an agent skill in
resources/boost/. Runphp artisan boost:install(orboost:update) after installing this package and your agent learns the workflow automatically. - Non-interactive by design: pass
--forceso commands never wait on a prompt. Without--force,dbml:syncin a shell with no TTY exits with code1and tells you to re-run with--forceinstead of hanging or silently doing nothing. - Preview first:
--dry-run(both commands) lists the files that would be written without touching models, migrations or the snapshot. - Machine-readable output:
--jsonprints one JSON report:{"success", "dry_run", "written": [paths], "skipped": [{target, reason}], "errors": [messages]}. - Reliable exit codes:
0on success,1on any error (missing file, parse error, reserved table name, unconfirmed prompt) — partial failures are never reported as success. - Agent workflow:
- Edit
database/schema.dbml. - Optionally preview:
php artisan dbml:sync database/schema.dbml --dry-run --json. - Run
php artisan dbml:sync database/schema.dbml --force --json(first time:php artisan dbml:generate database/schema.dbml --json) and check the exit code /errors. - Review the files listed in
written, thenphp artisan migrate.
- Edit
- Rules for agents: do not hand-write migrations for tables managed in DBML, never remove
@dbml-syncmarkers, and put custom model code outside the marker blocks. - LLM index: a concise
llms.txtsummarises the package for LLM tools.
⚙️ Customization
You can modify the generated model and migration templates by editing the stub files located in stubs/dbml-to-laravel/ after publishing them. This allows you to tailor the output to your specific project needs, including adding custom traits, interfaces, or modifying default property definitions.
Updating the bundled DBML parser (contributors only)
The published package already includes a fully bundled parser, so consumers never have to install Node dependencies. If you change bin/parse-dbml.js, run the following before opening a PR:
npm install npm run build-parser
Commit both the updated source file and the generated bin/parse-dbml.runtime.cjs artifact so downstream users continue to benefit from the prepackaged parser.
🤝 Contributing
We welcome contributions! Please see our CONTRIBUTING.md for details on how you can help improve this project. Whether it's bug fixes, new features, or documentation improvements, your input is valuable.
Contributor Documentation
Detailed contributor guides live in the docs/ directory:
| Document | Description |
|---|---|
| Getting Started | Clone to first green test |
| Architecture | 3-stage pipeline, component map, data flow |
| Adding Features | Recipe-style "how do I add X" guides |
| Stubs | Stub placeholders, override paths, customization |
| Parser Bundle | Node parser, esbuild bundle, JSON payload |
| Testing | Pest patterns, fixtures, adding test cases |
| Gotchas | Compatibility matrix, silent edge cases, traps |
❓ Support
For questions, bug reports, or feature requests, please open an issue on the GitHub Issues page. We'll do our best to respond promptly.
🎉 This package was featured by Laravel News. If you find it useful, give it a ⭐ on GitHub and share it with your Laravel team!
📄 License
This project is open-sourced software licensed under the MIT License.