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

Canvas Core Laravel Package

orchestra/canvas-core

Core utilities for Orchestra Canvas code generators. Build and customize generators for Laravel apps and packages, with testing and coverage support. Provides the foundational services used by Canvas to scaffold code and streamline development workflows.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Installation:

    composer require orchestra/canvas-core
    

    Ensure your project uses Laravel 11.x (or later compatible versions).

  2. Publish Configuration:

    php artisan vendor:publish --provider="Orchestra\Canvas\Core\CanvasServiceProvider"
    

    This creates a config/canvas.php file with default presets.

  3. First Command: Generate a basic model with migrations, factory, and tests:

    php artisan canvas:generate model User --with=migration,factory,test
    

    Verify the files are created in app/Models/User.php, database/migrations/..., etc.

  4. Explore Presets: Check config/canvas.php for built-in presets like model, controller, policy, and resource. Example for a controller:

    php artisan canvas:generate controller Admin/UserController --resource
    
  5. Customize Templates: Override default templates by copying files from vendor/orchestral/canvas-core/src/Resources/views to resources/views/vendor/canvas/.


Implementation Patterns

Core Workflows

1. Standardized Scaffolding

  • Use Case: Enforce team-wide conventions (e.g., naming, file structure).
  • Pattern:
    php artisan canvas:generate model Post --with=migration,seeder,policy,test
    
    Generates:
    • Model (app/Models/Post.php)
    • Migration (database/migrations/...)
    • Seeder (database/seeders/PostsTableSeeder.php)
    • Policy (app/Policies/PostPolicy.php)
    • Test (tests/Feature/PostTest.php)

2. Package Development

  • Use Case: Scaffold reusable package structures (e.g., service providers, CLI commands).
  • Pattern: Define a custom preset in config/canvas.php:
    'presets' => [
        'package' => [
            'path' => 'stubs/package',
            'files' => [
                'Provider' => 'src/Providers/{Name}ServiceProvider.php',
                'Command' => 'src/Console/Commands/{Name}Command.php',
            ],
        ],
    ],
    
    Then generate:
    php artisan canvas:generate package MyPackage --with=Provider,Command
    

3. Dynamic Generation in CI/CD

  • Use Case: Auto-generate boilerplate in pre-commit hooks or deployment pipelines.
  • Pattern: Add to composer.json scripts:
    "scripts": {
        "post-create-project-cmd": [
            "canvas:generate model User --with=migration,factory,test"
        ]
    }
    
    Or use a GitHub Action:
    - name: Generate Boilerplate
      run: php artisan canvas:generate model Post --with=migration,seeder
    

4. Extending with Custom Generators

  • Use Case: Add domain-specific generators (e.g., API resources, DTOs).
  • Pattern: Create a custom generator class:
    // app/Generators/ApiResourceGenerator.php
    namespace App\Generators;
    
    use Orchestra\Canvas\Core\GeneratesCode;
    
    class ApiResourceGenerator extends GeneratesCode
    {
        protected $signature = 'canvas:generate api-resource {name}';
        protected $description = 'Generate an API resource';
    
        public function generate()
        {
            $this->generateClass($this->name, 'api-resource', 'ApiResource');
        }
    }
    
    Register it in AppServiceProvider:
    public function boot()
    {
        $this->app->make('command.canvas.generate.api-resource')->register();
    }
    
    Now use:
    php artisan canvas:generate api-resource PostResource
    

5. Template Inheritance

  • Use Case: Reuse base templates across projects.
  • Pattern: Copy the default template from vendor/orchestral/canvas-core/src/Resources/views/model.stub to resources/views/vendor/canvas/model.stub and modify it. Example: Add a softDeletes trait to all generated models:
    <?php
    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Eloquent\SoftDeletes;
    
    class {{ class }} extends Model
    {
        use SoftDeletes;
    
        // ...
    }
    

Integration Tips

  1. Leverage Laravel Facades: Use Laravel’s facades (e.g., Schema, Artisan) within generators for dynamic logic:

    use Illuminate\Support\Facades\Schema;
    
    public function generate()
    {
        Schema::create($this->name.'s', function ($table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
    }
    
  2. Combine with Workbench Actions: Use orchestra/workbench actions to extend generators with business logic:

    use Orchestra\Workbench\Actions\Action;
    
    class AddSoftDeletes extends Action
    {
        public function handle()
        {
            // Add soft deletes to the generated model
        }
    }
    
  3. Dynamic File Paths: Use Illuminate\Filesystem\join_paths() for cross-platform compatibility:

    use Illuminate\Filesystem\Filesystem;
    use Illuminate\Support\Facades\Storage;
    
    $path = join_paths(app_path(), 'Models', $this->name.'.php');
    
  4. Event Listeners: Trigger events after generation to run additional logic:

    use Orchestra\Canvas\Core\Events\CodeHasBeenGenerated;
    
    CodeHasBeenGenerated::dispatch($this->name);
    
  5. Testing Generators: Use Laravel’s testing tools to verify generator output:

    public function test_model_generator()
    {
        $this->artisan('canvas:generate model TestModel')
             ->expectsOutput('Model created successfully.')
             ->assertExitCode(0);
    
        $this->assertFileExists(app_path('Models/TestModel.php'));
    }
    

Gotchas and Tips

Pitfalls

  1. Generator Registration:

    • Issue: Custom generators may not register if not properly bound in the service container.
    • Fix: Ensure the generator is registered in a service provider:
      $this->app->bind('command.canvas.generate.my-generator', function ($app) {
          return new \App\Generators\MyGenerator();
      });
      
  2. Template Path Conflicts:

    • Issue: Custom templates in resources/views/vendor/canvas/ may override defaults unexpectedly.
    • Fix: Use unique subdirectories (e.g., resources/views/vendor/canvas/myapp/) and update config/canvas.php:
      'paths' => [
          'templates' => resource_path('views/vendor/canvas/myapp'),
      ],
      
  3. Laravel Version Mismatch:

    • Issue: The package explicitly targets Laravel 11.x. Upgrading to Laravel 12+ may break functionality.
    • Fix: Monitor the GitHub issues for compatibility updates or fork the package.
  4. Null Generators Array:

    • Issue: Passing null to the generators config key can cause errors.
    • Fix: Always ensure generators is an array:
      'generators' => [
          'model' => ['migration', 'factory', 'test'],
      ],
      
  5. Soft Deprecations:

    • Issue: Methods like possibleModelsUsingCanvas() are soft-deprecated.
    • Fix: Use Laravel’s native methods (e.g., possibleModels()) instead.
  6. PHP Attributes:

    • Issue: Generators using PHP 8 attributes may not work in older PHP versions.
    • Fix: Ensure your project uses PHP 8.1+ and check for attribute usage in custom generators.
  7. Migration Generator Conflicts:

    • Issue: Overriding Laravel’s default MigrationGeneratorCommand may cause conflicts.
    • Fix: Extend the command instead of replacing it:
      use Illuminate\Database\Console\Migrations\MigrationGeneratorCommand;
      
      class CustomMigrationGenerator extends MigrationGeneratorCommand
      {
          // Extend logic here
      }
      

Debugging Tips

  1. Enable Debug Mode: Set debug to true in config/canvas.php to log generator actions:

    'debug' => env('CANVAS_DEBUG', false),
    
  2. Check Generator Output: Use --verbose flag to see detailed generation steps:

    php artisan canvas:generate model User --verbose
    
  3. Inspect Template Rendering: Add debug statements in stub templates to trace variable replacements:

    {{ dump($variables) }}
    
  4. Validate File Permissions: Ensure the target directory (e.g., `app

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.
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
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope