### Install Blueprint Source: https://context7.com/laravel-shift/blueprint/llms.txt Install Blueprint as a dev dependency using Composer. Optionally, install additional test assertions. ```bash composer require -W --dev laravel-shift/blueprint # Optional: install additional test assertions for generated tests composer require --dev jasonmccreary/laravel-test-assertions ``` -------------------------------- ### Install Laravel Blueprint Source: https://github.com/laravel-shift/blueprint/blob/master/README.md Install Blueprint as a development dependency using Composer. This command ensures that Blueprint is available for your project. ```sh composer require -W --dev laravel-shift/blueprint ``` -------------------------------- ### Full End-to-End Example: Blog Application Scaffold Source: https://context7.com/laravel-shift/blueprint/llms.txt Scaffolds a complete blog application including models with relationships, CRUD web controllers, and API resource controllers from a single draft file. ```yaml # draft.yaml models: User: name: string email: string unique password: string Category: name: string:100 unique slug: string:100 unique Post: title: string:400 slug: string:400 unique content: longtext published_at: nullable timestamp author_id: id:user category_id: id relationships: belongsToMany: Tag Tag: name: string:50 unique relationships: belongsToMany: Post Comment: body: text user_id: id relationships: belongsTo: Post controllers: Post: resource: web # full CRUD: index, create, store, show, edit, update, destroy Api\Post: resource: api # JSON API: index, store, show, update, destroy Api\Comment: resource: api meta: parent: Post # nested: /posts/{post}/comments ``` ```bash php artisan blueprint:build # CREATED Model app/Models/User.php # CREATED Model app/Models/Category.php # CREATED Model app/Models/Post.php # CREATED Model app/Models/Tag.php ``` -------------------------------- ### Draft File: Model Definition Example Source: https://context7.com/laravel-shift/blueprint/llms.txt Defines models, their properties, and relationships using a concise YAML grammar. Blueprint infers `id`, `timestamps`, and `belongsTo` relationships. ```yaml models: Post: title: string:400 content: longtext published_at: nullable timestamp author_id: id:user # foreign key → users table, infers belongsTo User Product: uuid # shorthand: id: uuid primary name: string price: decimal:10,2 status: enum:draft,published,archived default:draft meta: json nullable timestamps: false # disable created_at / updated_at softDeletes # adds deleted_at column + SoftDeletes trait Comment: body: text user_id: id foreign:users.id onDelete:cascade relationships: belongsTo: Post, User morphTo: Commentable ``` -------------------------------- ### Blueprint YAML Definition Example Source: https://github.com/laravel-shift/blueprint/blob/master/README.md Example of a Blueprint draft file defining models and controllers. This YAML syntax specifies the structure and behavior of generated Laravel components. ```yaml models: Post: title: string:400 content: longtext published_at: nullable timestamp author_id: id:user controllers: Post: index: query: all render: post.index with:posts store: validate: title, content, author_id save: post send: ReviewPost to:post.author.email with:post dispatch: SyncMedia with:post fire: NewPost with:post flash: post.title redirect: posts.index ``` -------------------------------- ### Custom Repository Generator Implementation Source: https://context7.com/laravel-shift/blueprint/llms.txt Implement the `Blueprint\Contracts\Generator` interface to create a custom generator. This example shows a `RepositoryGenerator` that creates repository files for models. ```php [['Repository', $path], ...]] */ public function output(Tree $tree): array { $output = ['created' => []]; foreach ($tree->models() as $model) { $name = $model->name(); $path = app_path("Repositories/{$name}Repository.php"); $stub = "files->ensureDirectoryExists(dirname($path)); $this->files->put($path, $stub); $output['created'][] = ['Repository', $path]; } return $output; } } ``` -------------------------------- ### Install Laravel Test Assertions Source: https://github.com/laravel-shift/blueprint/blob/master/README.md Install the additional assertions package if you plan to run tests generated by Blueprint. This is a development dependency. ```sh composer require --dev jasonmccreary/laravel-test-assertions ``` -------------------------------- ### Swap Generator at Runtime Source: https://context7.com/laravel-shift/blueprint/llms.txt Alternatively, swap a built-in generator with your custom implementation at runtime, for example, within a ServiceProvider. ```php // In a ServiceProvider $blueprint = app(\Blueprint\Blueprint::class); $blueprint->swapGenerator( \Blueprint\Generators\ModelGenerator::class, new \App\Blueprint\CustomModelGenerator(app('files')) ); ``` -------------------------------- ### Register Custom Shorthand in AppServiceProvider Source: https://context7.com/laravel-shift/blueprint/llms.txt Register custom YAML shorthands within the `AppServiceProvider::boot()` method. This example adds an 'auditable' shorthand for created_by and updated_by columns. ```php use Blueprint\Blueprint; // In AppServiceProvider::boot() $blueprint = app(Blueprint::class); // Adds "auditable" shorthand that expands to created_by and updated_by columns $blueprint->registerShorthand('auditable', function (array $matches): string { return $matches[1] . "created_by: id\n" . $matches[1] . 'updated_by: id'; }); ``` -------------------------------- ### Initialize Draft File with blueprint:new Source: https://context7.com/laravel-shift/blueprint/llms.txt Creates a starter `draft.yaml` and traces existing models. Optionally publishes configuration or custom stubs. ```bash php artisan blueprint:new # Also publish the Blueprint configuration file php artisan blueprint:new --config # Also publish customizable stubs to stubs/blueprint/ php artisan blueprint:new --stubs ``` -------------------------------- ### Publish Blueprint Configuration Source: https://context7.com/laravel-shift/blueprint/llms.txt Use this command to publish the Blueprint configuration file to your project. ```bash php artisan vendor:publish --tag=blueprint-config ``` -------------------------------- ### Build Syntax Tree with Blueprint::analyze() Source: https://context7.com/laravel-shift/blueprint/llms.txt Builds a syntax tree from parsed tokens, resolving models and controllers for generators. Requires parsed tokens and optionally a 'cache' key for previously traced models. ```php use Blueprint\Blueprint; $blueprint = app(Blueprint::class); $tokens = $blueprint->parse($yaml); $tokens['cache'] = []; // previously traced models $tree = $blueprint->analyze($tokens); foreach ($tree->models() as $name => $model) { echo $model->name(); // "Post" echo $model->tableName(); // "posts" echo $model->fullyQualifiedClassName(); // "App\Models\Post" print_r(array_keys($model->columns())); // ['id', 'title', ...] print_r($model->relationships()); // ['belongsTo' => ['User'], ...] } foreach ($tree->controllers() as $name => $controller) { echo $controller->className(); // "PostController" print_r(array_keys($controller->methods())); // ['index', 'store', ...] } ``` -------------------------------- ### Generate Components with blueprint:build Source: https://context7.com/laravel-shift/blueprint/llms.txt Reads `draft.yaml` and generates Laravel components. Supports options to specify generation scope or overwrite existing files. ```bash # Build from the default draft.yaml / draft.yml php artisan blueprint:build # Build from a custom draft file php artisan blueprint:build path/to/custom-draft.yaml # Only generate models and migrations, skip everything else php artisan blueprint:build --only=models,migrations # Generate everything except tests php artisan blueprint:build --skip=tests # Overwrite existing migration files in-place php artisan blueprint:build --overwrite-migrations ``` -------------------------------- ### Blueprint Configuration File Source: https://context7.com/laravel-shift/blueprint/llms.txt Customize namespaces, paths, foreign key constraints, stub generation, and active generators by modifying this configuration file. ```php // config/blueprint.php return [ 'namespace' => 'App', 'models_namespace' => 'Models', // App\Models 'controllers_namespace' => 'Http\\Controllers', 'app_path' => 'app', 'generate_phpdocs' => false, // add @property PHPDoc blocks to models 'use_constraints' => false, // add foreign key constraints to migrations 'on_delete' => 'cascade', // cascade | restrict | no_action | null 'on_update' => 'cascade', 'fake_nullables' => true, // generate fake data for nullable columns in factories 'use_guarded' => false, // use $guarded = [] instead of $fillable 'property_promotion' => false, // use constructor property promotion 'singular_routes' => false, // use singular route names 'generate_resource_collection_classes' => true, 'types' => [ 'primary' => 'id', // default primary key type 'timestamps' => 'timestamp', // timestamp | timestampTz ], // Swap or add custom generators 'generators' => [ 'controller' => \Blueprint\Generators\ControllerGenerator::class, 'factory' => \Blueprint\Generators\FactoryGenerator::class, 'migration' => \Blueprint\Generators\MigrationGenerator::class, 'model' => \Blueprint\Generators\ModelGenerator::class, 'route' => \Blueprint\Generators\RouteGenerator::class, 'seeder' => \Blueprint\Generators\SeederGenerator::class, 'test' => \Blueprint\Generators\PhpUnitTestGenerator::class, // 'test' => \Blueprint\Generators\PestTestGenerator::class, // swap to Pest 'event' => \Blueprint\Generators\Statements\EventGenerator::class, 'form_request' => \Blueprint\Generators\Statements\FormRequestGenerator::class, 'job' => \Blueprint\Generators\Statements\JobGenerator::class, 'mail' => \Blueprint\Generators\Statements\MailGenerator::class, 'notification' => \Blueprint\Generators\Statements\NotificationGenerator::class, 'resource' => \Blueprint\Generators\Statements\ResourceGenerator::class, 'view' => \Blueprint\Generators\Statements\ViewGenerator::class, 'inertia_page' => \Blueprint\Generators\Statements\InertiaPageGenerator::class, 'policy' => \Blueprint\Generators\PolicyGenerator::class, ], ]; ``` -------------------------------- ### Generate Files with Blueprint::generate() Source: https://context7.com/laravel-shift/blueprint/llms.txt Runs generators against the syntax tree and writes files. Supports filtering generators with `only` or `skip` arrays, and options like `overwriteMigrations`. ```php use Blueprint\Blueprint; $blueprint = app(Blueprint::class); $tree = $blueprint->analyze($blueprint->parse($yaml)); // Generate everything $generated = $blueprint->generate($tree); // Generate only models and migrations $generated = $blueprint->generate($tree, only: ['models', 'migrations']); // Generate everything except tests $generated = $blueprint->generate($tree, skip: ['controllers', 'requests', 'views']); // Overwrite existing migration files $generated = $blueprint->generate($tree, overwriteMigrations: true); // $generated structure: // [ // 'created' => [ // ['Model', 'app/Models/Post.php'], // ['Migration', 'database/migrations/2024_01_01_000001_create_posts_table.php'], // ['Controller', 'app/Http/Controllers/PostController.php'], // ['Form Request', 'app/Http/Requests/StorePostRequest.php'], // ], // 'updated' => [...], // 'deleted' => [...], // ] foreach ($generated['created'] ?? [] as [$type, $path]) { echo "Created {$type}: {$path}\n"; } ``` -------------------------------- ### Build Laravel Components with Blueprint Source: https://github.com/laravel-shift/blueprint/blob/master/README.md Use the `blueprint:build` Artisan command to generate Laravel components based on your Blueprint definition file. Ensure your draft file is correctly configured. ```sh php artisan blueprint:build ``` -------------------------------- ### Publish Customizable Blueprint Stubs Source: https://context7.com/laravel-shift/blueprint/llms.txt Copies all Blueprint stub templates to `stubs/blueprint/` for customization. Blueprint prioritizes these custom stubs over its built-in ones. ```bash php artisan blueprint:stubs # Stubs are published to: # stubs/blueprint/model.class.stub # stubs/blueprint/controller.class.stub # stubs/blueprint/controller.method.stub # stubs/blueprint/migration.stub # stubs/blueprint/factory.stub # stubs/blueprint/request.stub # stubs/blueprint/resource.stub # ... (and many more) ``` -------------------------------- ### Use Resource Shorthand for Controllers in YAML Source: https://context7.com/laravel-shift/blueprint/llms.txt Employ 'resource: web' or 'resource: api' to automatically expand all standard CRUD methods without explicitly listing each action. You can also define partial resources by specifying only the desired methods. ```yaml controllers: Article: resource: web # expands index, create, store, show, edit, update, destroy # Partial resource — only specific methods Category: resource: index, store, destroy # API resource controller → returns JSON resources Product: resource: api # expands api.index, api.store, api.show, api.update, api.destroy ``` -------------------------------- ### Draft File: Column Data Types and Modifiers Source: https://context7.com/laravel-shift/blueprint/llms.txt Illustrates various column data types and modifiers supported in Blueprint's draft file for defining database schema. ```yaml models: Profile: # Strings username: string # varchar(255) bio: string:1000 # varchar(1000) description: text notes: longtext # Numbers age: integer score: float balance: decimal:12,4 votes: biginteger unsigned # Booleans & Dates is_active: boolean default:true born_on: date nullable verified_at: nullable timestamp # Special types locale: char:5 tags: json ip_addr: ipaddress uid: uuid kind: enum:admin,user,guest # Relationship keys team_id: id # foreignId → bigInteger unsigned org_id: id:organization # FK referencing organizations table # Modifiers slug: string unique rank: integer default:0 index token: string:100 nullable default:null comment:'Auth token' ``` -------------------------------- ### Generate Controllers with Authorization Policies Source: https://context7.com/laravel-shift/blueprint/llms.txt Attach authorization policies to controllers using the `policies` meta key. Policies can be generated for all resource abilities or specific methods. ```yaml controllers: Post: meta: policies: true # generates PostPolicy with all resource abilities + authorizeResource() in constructor resource: web Comment: meta: policies: index, store # generates policy only for specified methods index: query: all render: comment.index with:comments store: validate: comment save: comment redirect: comments.index ``` -------------------------------- ### Generate Nested and Invokable Controllers Source: https://context7.com/laravel-shift/blueprint/llms.txt Configure controller generation, including nested namespaces, resource types, and invokable single-action controllers with explicit statements. ```yaml controllers: # Nested controller: generates App\Http\Controllers\Api\PostController Api\Post: resource: api # Nested resource with parent model (e.g. /posts/{post}/comments) Comment: resource: api meta: parent: Post # Invokable single-action controller Dashboard: invokable: true # generates __invoke method; renders dashboard view # Invokable with explicit statements ExportReport: invokable: query: all:reports respond: reports ``` -------------------------------- ### Register Custom Generator in Config Source: https://context7.com/laravel-shift/blueprint/llms.txt Register your custom generator by adding an entry to the `generators` array in `config/blueprint.php`. ```php 'generators' => [ // ... existing generators ... 'repository' => \App\Blueprint\RepositoryGenerator::class, ], ``` -------------------------------- ### Define Controller Actions in YAML Source: https://context7.com/laravel-shift/blueprint/llms.txt Controllers are declared under the 'controllers' key. Each action lists statements that Blueprint translates into PHP controller code, with automatic import resolution. ```yaml controllers: Post: index: query: all # $posts = Post::all() render: post.index with:posts # return view('post.index', compact('posts')) create: render: post.create # return view('post.create') store: validate: title, content # use StorePostRequest form request save: post # $post = Post::create($request->validated()) flash: post.id # session()->flash('post.id', $post->id) redirect: posts.index # return redirect()->route('posts.index') show: render: post.show with:post # return view('post.show', compact('post')) edit: render: post.edit with:post update: validate: title, content update: post flash: post.id redirect: posts.index destroy: delete: post # $post->delete() redirect: posts.index ``` -------------------------------- ### Trace Existing Eloquent Models Source: https://context7.com/laravel-shift/blueprint/llms.txt Scan existing Eloquent model classes to cache their column definitions. This allows referencing models in future drafts without re-declaring them. Use `--path` to specify custom model directories. ```bash # Trace models from default app/Models path php artisan blueprint:trace ``` ```bash # Trace from one or more custom paths php artisan blueprint:trace --path=app/Domain/Blog --path=app/Domain/Auth ``` -------------------------------- ### Parse Draft YAML Programmatically with Blueprint::parse() Source: https://context7.com/laravel-shift/blueprint/llms.txt Parses a YAML string into a PHP array of tokens, handling shorthand expansions and duplicate keys. Ensure Blueprint is resolved from the application container. ```php use Blueprint\Blueprint; $blueprint = app(Blueprint::class); $yaml = <<<'YAML' models: Post: title: string published_at: nullable timestamp uuid # shorthand controllers: Post: resource: web YAML; $tokens = $blueprint->parse($yaml); // [ // 'models' => [ // 'Post' => [ // 'title' => 'string', // 'published_at' => 'nullable timestamp', // 'id' => 'uuid primary', // expanded shorthand // ] // ], // 'controllers' => [ // 'Post' => ['resource' => 'web'] // ] // ] ``` -------------------------------- ### Configure Model Meta Options in YAML Source: https://context7.com/laravel-shift/blueprint/llms.txt Use the 'meta' block to configure advanced model settings such as custom table names, database connections, pivot models, parent classes, and custom traits or interfaces. ```yaml models: # Custom table name and connection LegacyOrder: meta: table: old_orders connection: legacy_db total: decimal:10,2 status: string # UUID primary key via shorthand ApiToken: uuid # expands to: id: uuid primary token: string:64 scopes: json # Pivot model with timestamps RoleUser: meta: pivot: true user_id: id role_id: id granted_by: id:user nullable timestamps # adds created_at/updated_at # Extend a custom base class and use traits AuditablePost: meta: extends: App\Models\BaseModel traits: App\Concerns\Auditable, App\Concerns\Searchable implements: App\Contracts\Publishable title: string body: text ``` -------------------------------- ### Undo Last Blueprint Build Source: https://context7.com/laravel-shift/blueprint/llms.txt Deletes all files created by the most recent `blueprint:build` command, using paths recorded in `.blueprint`. Existing files that were only updated are reported but not reverted. ```bash php artisan blueprint:erase # Output: # Deleted: # - app/Models/Post.php # - database/migrations/2024_01_01_000000_create_posts_table.php # - app/Http/Controllers/PostController.php # ... ``` -------------------------------- ### Define Controller Statements in YAML Source: https://context7.com/laravel-shift/blueprint/llms.txt Build controller action bodies using statement keywords, which Blueprint maps to specific Laravel code patterns. This includes validation, saving, sending emails, dispatching jobs, and redirecting. ```yaml controllers: Order: store: validate: order # → StoreOrderRequest form request; rules from model columns save: order # → $order = Order::create($request->validated()) send: OrderConfirmation to:order.user.email with:order # → Mail::to()->send(new OrderConfirmation($order)) dispatch: ProcessPayment with:order # → ProcessPayment::dispatch($order) fire: OrderPlaced with:order # → OrderPlaced::dispatch($order) flash: order.id redirect: orders.index show: render: order.show with:order # → return view(...) apiShow: resource: OrderResource # → return new OrderResource($order) apiIndex: query: all resource: collection:orders # → return OrderCollection::make(Order::all()) delete: delete: order respond: 204 # → return response()->noContent() notify: notify: order.user with:ShipmentUpdate # → $order->user->notify(new ShipmentUpdate($order)) ``` -------------------------------- ### Define Model Relationships in YAML Source: https://context7.com/laravel-shift/blueprint/llms.txt Declare explicit relationships like hasMany, belongsToMany, belongsTo, and morphTo under the 'relationships' key in your model definitions. Blueprint also auto-infers 'belongsTo' from columns ending in '_id'. ```yaml models: User: name: string email: string unique Post: title: string user_id: id # auto-inferred: belongsTo User relationships: hasMany: Comment belongsToMany: Tag Tag: name: string relationships: belongsToMany: Post Comment: body: text relationships: belongsTo: Post, User morphTo: Commentable # polymorphic Image: url: string relationships: morphMany: Comment # polymorphic one-to-many ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.