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

Php Gitlab Api Laravel Package

m4tthumphrey/php-gitlab-api

Modern GitLab API v4 client for PHP 8.1–8.5. Provides a clean, feature-rich wrapper around GitLab endpoints with PSR-18 HTTP client and PSR-17 factories support, plus maintained releases, changelog, and strong community tooling.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Steps
1. **Installation**
   Add the package via Composer:
   ```bash
   composer require m4tthumphrey/php-gitlab-api:^12.1 guzzlehttp/guzzle:^7.9.2

For Laravel, use the framework-specific package:

composer require graham-campbell/gitlab:^8.1
  1. Basic Setup Initialize the client with authentication:

    use Gitlab\Client;
    
    $client = new Client();
    $client->authenticate('your_access_token', Client::AUTH_HTTP_TOKEN);
    
  2. First Use Case Fetch a project or create an issue:

    // Fetch a project
    $project = $client->projects()->show(123);
    
    // Create an issue
    $issue = $client->issues()->create(123, [
        'title' => 'Fix bug',
        'description' => 'This is a test issue.'
    ]);
    
  3. Self-Hosted GitLab Configure the API URL if using a self-hosted instance:

    $client->setUrl('https://git.yourdomain.com');
    

Implementation Patterns

Common Workflows

  1. CRUD Operations Use the fluent API for projects, issues, merge requests, etc.:

    // Create
    $project = $client->projects()->create('My Project', ['description' => 'Test']);
    
    // Read
    $project = $client->projects()->show($project->id);
    
    // Update
    $updated = $client->projects()->update($project->id, ['description' => 'Updated']);
    
    // Delete
    $client->projects()->delete($project->id);
    
  2. Pagination with ResultPager Fetch paginated results (e.g., issues, merge requests):

    $pager = new Gitlab\ResultPager($client);
    $issues = $pager->fetchAll($client->issues(), 'all', [123, ['state' => 'closed']]);
    
  3. Handling API Responses Use getResponse() for raw responses or getData() for parsed data:

    $response = $client->projects()->show(123);
    $data = $response->getData();
    
  4. Custom HTTP Clients Extend functionality with HTTPlug plugins (e.g., caching, logging):

    use Http\Client\Common\Plugin\HeaderSetPlugin;
    use Gitlab\HttpClient\Builder;
    
    $plugin = new HeaderSetPlugin(['User-Agent' => 'MyApp/1.0']);
    $builder = new Builder();
    $builder->addPlugin($plugin);
    
    $client = new Client($builder);
    
  5. Error Handling Catch exceptions for API errors:

    try {
        $client->projects()->show(9999); // Non-existent project
    } catch (\Gitlab\Exception\GitlabException $e) {
        \Log::error($e->getMessage());
    }
    
  6. Authentication Methods

    • Personal Access Token (default):
      $client->authenticate('token', Client::AUTH_HTTP_TOKEN);
      
    • OAuth2 Token:
      $client->authenticate('oauth_token', Client::AUTH_OAUTH_TOKEN);
      
    • Job Token (for CI/CD):
      $client->authenticate('job_token', Client::AUTH_JOB_TOKEN);
      
  7. Search Functionality Search across projects, groups, or issues:

    $results = $client->search()->all('keyword', ['search' => 'scope:projects']);
    
  8. Webhooks and Events Listen to project/group events or manage webhooks:

    $webhook = $client->projects()->addWebhook(123, [
        'url' => 'https://example.com/webhook',
        'push_events' => true
    ]);
    

Gotchas and Tips

Pitfalls

  1. Double Encoding in URLs

    • Some endpoints (e.g., Repositories::compareCommits) may double-encode query parameters. Use rawurlencode or urlencode manually if needed:
      $client->repositories()->compareCommits(123, 'main', 'feature', ['params' => rawurlencode('key=value')]);
      
  2. Pagination Quirks

    • Older endpoints may not use ResultPager for pagination. Check the API docs for manual pagination handling:
      $page = 1;
      do {
          $issues = $client->issues()->all(123, ['page' => $page, 'per_page' => 100]);
          $page = $issues->nextPage();
      } while ($page);
      
  3. Authentication Scope

    • Ensure your access token has the required scopes (e.g., api for full access, read_repository for limited access). Use read_api for read-only operations:
      $client->authenticate('token_with_read_api_scope', Client::AUTH_HTTP_TOKEN);
      
  4. Rate Limiting

    • GitLab enforces rate limits (e.g., 60 requests per minute for unauthenticated requests). Implement exponential backoff for retries:
      use Symfony\Component\HttpClient\RetryStrategy;
      $client->setHttpClient($httpClient->withOptions([
          'timeout' => 30,
          'retry_on_status' => [429, 500, 502, 503, 504],
          'retry_delay' => RetryStrategy::DELAY_MILLISECONDS * 1000,
      ]));
      
  5. Sensitive Data Handling

    • Avoid logging or exposing tokens/passwords. Use environment variables or Laravel's .env:
      $token = env('GITLAB_ACCESS_TOKEN');
      $client->authenticate($token, Client::AUTH_HTTP_TOKEN);
      
  6. Deprecated Methods

    • Some methods (e.g., Projects::pipelines with date filters) may require time information. Update to use ResultPager for consistency:
      // Old (may fail)
      $client->projects()->pipelines(123, ['before' => '2023-01-01']);
      
      // New (recommended)
      $pager = new ResultPager($client);
      $pipelines = $pager->fetchAll($client->projects()->pipelines(123), 'all', [123, ['before' => '2023-01-01T00:00:00Z']]);
      
  7. Self-Hosted GitLab URL

    • Forgetting to set setUrl() for self-hosted instances will default to https://gitlab.com. Always verify:
      $client->setUrl('https://git.yourdomain.com');
      
  8. Merge Request Conflicts

    • When updating merge requests, handle conflicts gracefully:
      try {
          $client->mergeRequests()->update(123, ['title' => 'Updated Title']);
      } catch (\Gitlab\Exception\GitlabException $e) {
          if (strpos($e->getMessage(), 'conflict') !== false) {
              // Resolve conflicts manually or programmatically
          }
      }
      

Debugging Tips

  1. Enable Debugging Use Guzzle middleware to log requests/responses:

    use GuzzleHttp\Middleware;
    use Psr\Http\Message\RequestInterface;
    
    $history = [];
    $client->setHttpClient($httpClient->withMiddleware([
        Middleware::tap(function (RequestInterface $request) use (&$history) {
            $history[] = $request;
        }),
        Middleware::history($history),
    ]));
    
  2. Check API Status Verify GitLab API availability before debugging:

    try {
        $client->system()->info();
    } catch (\Gitlab\Exception\GitlabException $e) {
        \Log::error('GitLab API unavailable: ' . $e->getMessage());
    }
    
  3. Validate Parameters Use OptionsResolver for parameter validation (e.g., for Projects::create):

    $resolver = new \Symfony\Component\OptionsResolver\OptionsResolver();
    $resolver->setDefaults([
        'name' => null,
        'description' => '',
        'visibility' => 'private',
    ]);
    $options = $resolver->resolve($inputParams);
    
  4. Handle Deprecated Features

Extension Points

  1. Custom API Endpoints Extend the client to support und
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.
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
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata