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

Packagist Api Laravel Package

spatie/packagist-api

Search Packagist and fetch package details via the official Packagist API. Provides a simple PackagistClient built on Guzzle with a URL generator, plus helpers to list all packages or filter by vendor/type, and browse popular packages with pagination.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require spatie/packagist-api
    

    No additional configuration is required—just autoload the package.

  2. First Use Case: Fetch basic package info (e.g., laravel/framework):

    use Spatie\PackagistApi\Packagist;
    
    $packagist = new Packagist();
    $package = $packagist->find('laravel/framework');
    dd($package->name, $package->description, $package->version);
    
  3. Key Classes:

    • Spatie\PackagistApi\Packagist: Main facade for API interactions.
    • Spatie\PackagistApi\Models\Package: Represents a Packagist package (e.g., laravel/framework).
    • Spatie\PackagistApi\Models\PackageVersion: Represents a specific version of a package.

Where to Look First

  • API Documentation: Understand the raw endpoints the package wraps.
  • Source Code: Check src/Packagist.php for available methods.
  • Tests: Real-world usage examples (e.g., searching, version comparisons).

Implementation Patterns

Core Workflows

1. Fetching Package Metadata

// Get a single package
$package = $packagist->find('spatie/laravel-backup');

// Get all versions of a package
$versions = $packagist->findVersions('spatie/laravel-backup');

2. Searching Packages

// Search by keyword (returns a collection of Package objects)
$results = $packagist->search('laravel', 10); // Limit to 10 results

3. Version-Specific Operations

// Get a specific version
$version = $packagist->findVersion('laravel/framework', '10.0.0');

// Compare versions (e.g., check if a version is stable)
if ($version->isStable()) {
    // Logic for stable versions
}

4. Dependency Resolution

// Get dependencies for a package/version
$dependencies = $packagist->findVersion('spatie/laravel-backup', '6.0.0')->dependencies;

// Check if a package requires PHP 8.0+
$phpVersion = $packagist->find('spatie/laravel-backup')->require->php;

5. Caching Responses

The package uses PSR-6 caching (via Spatie\PackagistApi\Cache\Cache). Configure it in config/packagist-api.php:

'cache' => [
    'driver' => 'file', // or 'array', 'database', etc.
    'prefix' => 'packagist_',
],

Enable caching for frequent requests:

$packagist = new Packagist(config('packagist-api.cache'));

Integration Tips

Laravel Service Providers

Bind the Packagist class to the container for easy dependency injection:

// In AppServiceProvider
$this->app->singleton(Packagist::class, function ($app) {
    return new Packagist(config('packagist-api.cache'));
});

Now inject it anywhere:

public function __construct(private Packagist $packagist) {}

Artisan Commands

Useful for CLI tools (e.g., checking package compatibility):

use Spatie\PackagistApi\Packagist;

class CheckPackageCommand extends Command {
    protected $signature = 'package:check {package}';
    protected $description = 'Check package metadata';

    public function handle(Packagist $packagist) {
        $package = $packagist->find($this->argument('package'));
        $this->info("Package: {$package->name}");
        $this->line("Latest version: {$package->version}");
    }
}

Event Listeners

Trigger actions when package updates are detected (e.g., for a "Package Monitor"):

$packagist = new Packagist();
$latestVersion = $packagist->find('spatie/laravel-backup')->version;

if ($latestVersion !== cache('last_backup_version')) {
    cache()->put('last_backup_version', $latestVersion);
    event(new PackageUpdated($packageName, $latestVersion));
}

Testing

Mock the Packagist class in tests:

$mock = Mockery::mock(Packagist::class);
$mock->shouldReceive('find')
     ->with('spatie/laravel-backup')
     ->andReturn((new Package())->setName('spatie/laravel-backup'));

$this->app->instance(Packagist::class, $mock);

Gotchas and Tips

Pitfalls

  1. Rate Limiting:

    • Packagist’s API has rate limits. Cache aggressively or implement retries for 429 responses.
    • Example retry logic:
      try {
          $package = $packagist->find('laravel/framework');
      } catch (RateLimitExceededException $e) {
          sleep(60); // Wait for rate limit to reset
          retry();
      }
      
  2. Deprecated Packages:

    • Some packages may return null or throw exceptions if they’re deleted from Packagist. Handle gracefully:
      $package = $packagist->find('nonexistent/package');
      if (!$package) {
          $this->error('Package not found on Packagist.');
      }
      
  3. Version Parsing:

    • The PackageVersion model includes methods like isStable(), isDev(), and isRC(), but edge cases (e.g., custom version strings) may break parsing. Validate versions manually if needed:
      if (!Version::isValid($versionString)) {
          throw new InvalidArgumentException("Invalid version format: {$versionString}");
      }
      
  4. Caching Invalidation:

    • The cache is not auto-invalidated when packages update on Packagist. Clear it manually or implement a cron job:
      // Clear cache every hour
      $schedule->command('cache:clear')->hourly();
      

Debugging

  1. Enable Debugging: Set the debug config option to log API requests:

    'debug' => env('PACKAGIST_DEBUG', false),
    

    Check logs for raw API responses.

  2. API Response Inspection: The Packagist class returns Spatie\PackagistApi\Models\Package objects, but you can access the raw response via:

    $rawResponse = $packagist->getRawResponse('laravel/framework');
    
  3. Common Exceptions:

    • PackageNotFoundException: Thrown when a package doesn’t exist.
    • InvalidArgumentException: Invalid package name/version format.
    • RateLimitExceededException: Hit API rate limits.

Tips

  1. Batch Fetching: For multiple packages, use findMany() to reduce API calls:

    $packages = $packagist->findMany(['laravel/framework', 'spatie/laravel-backup']);
    
  2. Version Comparison: Use the Version helper class for semantic versioning:

    use Spatie\PackagistApi\Support\Version;
    
    if (Version::isGreaterThan('10.0.0', '9.0.0')) {
        // Logic for newer versions
    }
    
  3. Custom Endpoints: The package wraps Packagist’s API but doesn’t expose all endpoints. For unsupported endpoints (e.g., /packages.json), extend the Packagist class:

    class CustomPackagist extends Packagist {
        public function getPackagesJson() {
            return $this->get('https://packagist.org/packages.json');
        }
    }
    
  4. Performance:

    • Lazy-load dependencies: Access dependencies only when needed to avoid heavy API responses.
    • Use findVersion() instead of find() if you need specific version data.
  5. Local Development: Mock the API during development to avoid hitting rate limits:

    $packagist = new Packagist(['cache' => ['driver' => 'array']]);
    $packagist->setBaseUrl('http://localhost:8000'); // Point to a local Packagist instance
    
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
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
twbs/bootstrap4