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

A base PackageServiceProvider for Laravel package authors. Quickly register and publish config, views, translations, assets, routes, migrations, commands, view components/composers, and install commands—all via a clean, fluent API.

View on GitHub
Deep Wiki
Context7

Getting Started

Start by installing the package in your Laravel project:

composer require spatie/laravel-package-tools

For new packages, use the package-skeleton-laravel repo as a template. It's pre-configured for this package.

First use case: Register your package's core features in YourPackageServiceProvider:

use Spatie\LaravelPackageTools\PackageServiceProvider;
use Spatie\LaravelPackageTools\Package;

class YourPackageServiceProvider extends PackageServiceProvider
{
    public function configurePackage(Package $package): void
    {
        $package
            ->name('your-package')
            ->hasConfigFile()
            ->hasMigrations(['create_tables'])
            ->hasViewComponents('prefix', AlertComponent::class);
    }
}

Key files to examine first:

  1. src/YourPackageServiceProvider.php - Main configuration
  2. config/your-package.php - Default config file
  3. database/migrations/ - Migration stubs
  4. src/Components/ - View components

Implementation Patterns

Core Workflow

  1. Configuration Phase:

    // src/YourPackageServiceProvider.php
    public function configurePackage(Package $package): void
    {
        $package
            ->name('your-package')
            ->hasConfigFile()
            ->hasMigrations(['create_tables'])
            ->hasViewComponents('prefix', AlertComponent::class);
    }
    
  2. Package Registration:

    // In your composer.json
    {
        "extra": {
            "laravel": {
                "providers": [
                    "YourPackage\\YourPackageServiceProvider"
                ]
            }
        }
    }
    
  3. Installation Command (optional but recommended):

    // src/Commands/InstallCommand.php
    use Spatie\LaravelPackageTools\Commands\InstallCommand;
    
    class InstallCommand extends InstallCommand
    {
        protected function getOptions(): array
        {
            return [
                'publish-config' => 'Publish config file',
                'publish-migrations' => 'Publish migrations',
                'publish-assets' => 'Publish assets',
            ];
        }
    
        protected function getDefaultOptions(): array
        {
            return [
                'publish-config' => true,
                'publish-migrations' => true,
                'publish-assets' => true,
            ];
        }
    }
    

Common Patterns

1. Config Management:

// Register multiple config files
$package->hasConfigFile(['config1', 'config2']);

// Merge config with app config
config(['your-package.key' => 'value']);

// Publish with custom tag
$package->hasConfigFile('custom-config', 'your-package-custom');

2. Migration Handling:

// Register specific migrations
$package->hasMigrations(['create_tables', 'seed_data']);

// Auto-discover migrations
$package->discoversMigrations();

// Run migrations automatically
$package->hasMigrations(['create_tables'])->runsMigrations();

3. View Components:

// Register with namespace
$package->hasViewComponents('your', AlertComponent::class);

// Share data with all views
$package->sharesDataWithAllViews('package_version', '1.0.0');

// Register view composers
$package->hasViewComposer('*', function ($view) {
    $view->with('shared_data', 'value');
});

4. Asset Pipeline:

// Register assets
$package->hasAssets();

// Custom publish path
$package->hasAssets('custom-path');

// Versioned assets
$package->hasAssets('assets', 'your-package-assets-v1');

Integration Tips

1. With Laravel Packages:

// Register package routes
$package->hasRoutes(['web', 'api']);

// Register package commands
$package->hasCommands([
    YourFirstCommand::class,
    YourSecondCommand::class
]);

2. With Testing:

// In your package's tests
$package->hasTestSuite('tests');

// Mock package registration
$package->mockPackage();

3. With Publishing:

// Custom publish tags
$package->hasConfigFile('config', 'your-package-config-v2');

// Grouped publishing
$package->hasGroupedPublishables([
    'config' => ['config1', 'config2'],
    'migrations' => ['create_tables']
]);

Gotchas and Tips

Common Pitfalls

  1. Path Resolution Issues:

    • Problem: Paths in hasAssets(), hasViews(), etc. are relative to the service provider location (src/).
    • Fix: Use ../ for paths outside src/ (e.g., ../config/custom.php).
  2. Migration Timing:

    • Problem: Migrations might run before package config is loaded.
    • Fix: Use runsMigrations() carefully or rely on vendor:publish for migrations.
  3. Config Publishing Conflicts:

    • Problem: Config files might not merge properly if keys overlap.
    • Fix: Use config(['your-package.key' => value]) in boot() for runtime overrides.
  4. View Component Namespace Collisions:

    • Problem: Similar component names across packages can cause conflicts.
    • Fix: Use unique prefixes (e.g., your-package::component).
  5. Asset Versioning:

    • Problem: Cached assets might not update after package updates.
    • Fix: Include version in asset paths or use Laravel Mix versioning.

Debugging Tips

  1. Package Registration:

    php artisan package:discover
    

    Verify your package appears in the list.

  2. Publishable Tags:

    php artisan vendor:publish --tag=your-package-*
    

    Check all available tags.

  3. Configuration Loading:

    php artisan config:clear
    php artisan config:cache
    

    Clear caches if config changes aren't reflected.

  4. Service Provider Boot Order:

    // In your package's service provider
    public function boot()
    {
        \Log::info('Your package booted');
    }
    

    Check logs to verify boot order.

Advanced Tips

  1. Dynamic Configuration:

    $package->hasDynamicConfig(function () {
        return [
            'setting' => env('YOUR_PACKAGE_SETTING', 'default')
        ];
    });
    
  2. Conditional Features:

    if (app()->environment('local')) {
        $package->hasMigrations(['debug_tables']);
    }
    
  3. Custom Install Logic:

    $package->hasInstallCommand(function (InstallCommand $command) {
        $command
            ->publishConfigFile()
            ->publishMigrations()
            ->askToStarRepoOnGitHub()
            ->askToRunMigrations();
    });
    
  4. Package Dependencies:

    $package->hasDependency('spatie/laravel-activitylog', '^3.0');
    
  5. Lifecycle Hooks:

    $package->onActivation(function () {
        \Log::info('Package activated!');
    });
    
    $package->onDeactivation(function () {
        \Log::info('Package deactivated!');
    });
    

Extension Points

  1. Custom Publishables:

    $package->addPublishable(
        new PublishableFile('path/to/file', 'public/path')
    );
    
  2. Custom Tags:

    $package->addPublishableTag('custom-tag', function () {
        return [
            new PublishableFile('path/to/file', 'public/path')
        ];
    });
    
  3. Custom Commands:

    $package->hasCommand(YourCustomCommand::class)
            ->withOptions([
                'option1' => 'Description',
                'option2' => 'Description',
            ]);
    
  4. Custom Views:

    $package->hasViews('custom-views', 'path/to/views')
            ->withComposers(['view-name' => ViewComposer::class]);
    
  5. Custom Assets:

    $package->hasAssets('custom-assets', 'path/to/assets')
            ->withVersion('1.2.3');
    
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony