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 Package Tools Laravel Package

spatie/laravel-package-tools

Laravel package helper from Spatie providing a base PackageServiceProvider to quickly register and publish config, migrations, routes, views, translations, assets, commands, install scripts, view components/composers, and shared view data with minimal boilerplate.

View on GitHub
Deep Wiki
Context7

Getting Started

  1. Installation:

    composer require spatie/laravel-package-tools
    

    Use the package-skeleton-laravel repo as a starting point for your package structure.

  2. First Use Case: Extend PackageServiceProvider in your main service provider file (src/YourPackageServiceProvider.php):

    use Spatie\LaravelPackageTools\PackageServiceProvider;
    use Spatie\LaravelPackageTools\Package;
    
    class YourPackageServiceProvider extends PackageServiceProvider
    {
        public function configurePackage(Package $package): void
        {
            $package->name('your-package-name');
        }
    }
    

    This sets up the foundation for all package features.


Implementation Patterns

Core Workflow

  1. Package Configuration: Define all package features in configurePackage() method. Example:

    $package
        ->name('your-package')
        ->hasConfigFile()
        ->hasMigrations(['create_tables'])
        ->hasViewComponents('prefix', AlertComponent::class);
    
  2. Feature Registration:

    • Config: Place config files in config/your-package.php and call hasConfigFile().
    • Migrations: Place migrations in database/migrations/ and register with hasMigration() or discoversMigrations().
    • Routes: Place route files in routes/ and register with hasRoute().
    • Commands: Register commands in src/Commands/ with hasCommand().
  3. Publishing: Users publish package assets via:

    php artisan vendor:publish --tag=your-package-name-{feature}
    

    Example tags: your-package-name-config, your-package-name-assets.

  4. Install Command: Create a custom installer command by extending Spatie\LaravelPackageTools\Commands\InstallCommand:

    $package->hasInstallCommand(function(InstallCommand $command) {
        $command
            ->publishConfigFile()
            ->publishMigrations()
            ->askToStarRepoOnGitHub();
    });
    

Integration Tips

  • Dependency Injection: Use Laravel’s service container to bind package classes:
    $this->app->bind('your-package', function () {
        return new YourPackageService();
    });
    
  • Event Listeners: Register listeners in configurePackage():
    $package->registerEventListeners([
        \YourPackage\Listeners\YourListener::class,
    ]);
    
  • Service Providers: For complex logic, create additional providers in src/Providers/ and register them:
    $package->registerServiceProviders([
        \YourPackage\Providers\YourProvider::class,
    ]);
    

Gotchas and Tips

Pitfalls

  1. Path Resolution:

    • Paths in configurePackage() are relative to the src/ directory. Incorrect paths (e.g., ../config/your-package.php) will cause failures.
    • Example fix: Use absolute paths or verify relative paths against the skeleton structure.
  2. Migration Conflicts:

    • If migrations are auto-discovered (discoversMigrations()), ensure the database/migrations/ directory exists and contains valid migration files. Conflicts may arise if filenames or table names clash with existing migrations.
  3. Config Publishing:

    • If hasConfigFile() is called but the config file doesn’t exist, the package will fail silently. Always verify the file exists at config/your-package.php.
  4. Route Caching:

    • Routes registered via hasRoute() are cached. Clear the route cache (php artisan route:clear) if routes aren’t loading after updates.
  5. View Component Namespace:

    • View components must be in src/Components/. Misplaced components (e.g., in resources/views/) won’t register.

Debugging

  • Log Package Events: Use Laravel’s logging to debug package initialization:
    \Log::info('Package configured:', ['name' => $package->name()]);
    
  • Check Published Tags: Verify publishable tags with:
    php artisan vendor:publish --tag=your-package-name --help
    
  • Stub Files: For publishesServiceProvider(), ensure stub files (e.g., resources/stubs/YourProvider.php.stub) exist and are valid.

Extension Points

  1. Custom Publish Logic: Override the getPublishableItems() method in your service provider to add custom publishable items:

    public function getPublishableItems(): array
    {
        return [
            'custom-file' => [
                'from' => __DIR__.'/../path/to/file',
                'to' => config_path('custom-file.php'),
            ],
        ];
    }
    
  2. Dynamic Configuration: Use mergeConfigFrom in boot() to dynamically merge config:

    public function boot()
    {
        $this->mergeConfigFrom(
            __DIR__.'/../config/your-package.php',
            'your-package'
        );
    }
    
  3. Conditional Registration: Register features conditionally based on Laravel version or environment:

    if (app()->version() >= '9.0') {
        $package->hasViewComponents('prefix', Component::class);
    }
    
  4. Lifecycle Hooks: Use registeringPackage(), bootingPackage(), and bootedPackage() to hook into package lifecycle:

    protected function bootingPackage(): void
    {
        \Log::info('Package is booting!');
    }
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport