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.4. Provides a clean, php-github-api-inspired interface to GitLab endpoints, with PSR-18 HTTP client and PSR-17 factory support for flexible integration and authentication.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require m4tthumphrey/php-gitlab-api guzzlehttp/guzzle

For Laravel, use the dedicated package:

composer require graham-campbell/gitlab
  1. Basic Authentication:

    use Gitlab\Client;
    
    $client = new Client();
    $client->authenticate(env('GITLAB_TOKEN'), Client::AUTH_HTTP_TOKEN);
    
  2. First Use Case: Fetch a project by ID:

    $project = $client->projects()->show(123);
    

Key Entry Points

  • Client Initialization: new Gitlab\Client() (supports custom HTTP clients via Gitlab\HttpClient\Builder).
  • API Methods: Organized by resource (e.g., $client->projects(), $client->issues()).
  • Pagination: Use Gitlab\ResultPager for paginated endpoints (e.g., $client->issues()->all()).

Implementation Patterns

Common Workflows

1. Project Management

  • Create a Project:
    $project = $client->projects()->create('My Project', [
        'description' => 'Test project',
        'visibility' => 'private',
    ]);
    
  • List Projects with Filters:
    $projects = $client->projects()->all(['search' => 'backend']);
    

2. CI/CD Integration

  • Trigger a Pipeline:
    $pipeline = $client->projects()->createPipeline(123, [
        'ref' => 'main',
        'variables' => [['key' => 'ENV', 'value' => 'production']],
    ]);
    
  • Fetch Pipeline Jobs:
    $jobs = $client->projects()->pipelineJobs(123, 456); // project_id, pipeline_id
    

3. Merge Requests

  • Create a Merge Request:
    $mr = $client->mergeRequests()->create(123, [
        'source_branch' => 'feature-branch',
        'target_branch' => 'main',
        'title' => 'Fix bug',
    ]);
    
  • List Merge Requests with Pagination:
    $pager = new Gitlab\ResultPager($client);
    $mrs = $pager->fetchAll($client->mergeRequests(), 'all', [123, ['state' => 'opened']]);
    

4. Issues

  • Create an Issue:
    $issue = $client->issues()->create(123, [
        'title' => 'Bug report',
        'description' => 'Details here...',
    ]);
    
  • List Issues with Custom Filters:
    $issues = $client->issues()->all(123, [
        'state' => 'closed',
        'author_id' => 789,
    ]);
    

5. Webhooks

  • Create a Project Hook:
    $hook = $client->projects()->addHook(123, [
        'url' => 'https://example.com/webhook',
        'push_events' => true,
    ]);
    

Integration Tips

Laravel-Specific

  • Service Provider Binding:

    // config/services.php
    'gitlab' => [
        'token' => env('GITLAB_TOKEN'),
        'url' => env('GITLAB_URL', 'https://gitlab.com'),
    ];
    
    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(Gitlab\Client::class, function ($app) {
            $client = new Gitlab\Client();
            $client->setUrl(config('services.gitlab.url'));
            $client->authenticate(config('services.gitlab.token'), Gitlab\Client::AUTH_HTTP_TOKEN);
            return $client;
        });
    }
    
  • Facade Usage:

    use GrahamCampbell\GitLab\Facades\GitLab;
    
    $project = GitLab::projects()->show(123);
    

Custom HTTP Client

  • Add Headers/Plugins:
    $plugin = new Http\Client\Common\Plugin\HeaderSetPlugin([
        'User-Agent' => 'MyApp/1.0',
    ]);
    
    $builder = new Gitlab\HttpClient\Builder();
    $builder->addPlugin($plugin);
    
    $client = new Gitlab\Client($builder);
    

Error Handling

  • Global Exception Handling:
    try {
        $client->projects()->show(123);
    } catch (Gitlab\Exception\GitlabException $e) {
        Log::error('GitLab API Error: ' . $e->getMessage());
        // Handle specific error codes (e.g., 404 for missing project)
    }
    

Gotchas and Tips

Pitfalls

  1. Authentication:

    • Sensitive Data: Tokens are marked as sensitive in recent versions (PHP 8.2+). Avoid logging or exposing them.
    • Job Tokens: Use Gitlab\Client::AUTH_JOB_TOKEN for CI/CD job-specific access (e.g., $client->authenticate($CI_JOB_TOKEN, Client::AUTH_JOB_TOKEN)).
  2. Pagination:

    • Manual Pagination: Some endpoints (e.g., recent()) require explicit pagination via ResultPager:
      $pager = new Gitlab\ResultPager($client);
      $items = $pager->fetchAll($client->projects(), 'recent');
      
  3. Parameter Handling:

    • Double Encoding: Older versions had issues with URL-encoded parameters (fixed in v11.11+). Ensure parameters are passed as arrays or strings, not pre-encoded.
    • Date Filters: Use millisecond precision for date ranges (e.g., ['created_after' => '2023-01-01T00:00:00.000Z']).
  4. Rate Limiting:

    • GitLab enforces rate limits. Cache responses or implement exponential backoff:
      use Http\Client\Common\Plugin\RetryPlugin;
      
      $retryPlugin = new RetryPlugin();
      $builder->addPlugin($retryPlugin);
      
  5. Self-Hosted GitLab:

    • Always set the custom URL:
      $client->setUrl('https://git.example.com');
      
    • API versions may differ from gitlab.com. Check your instance’s API docs.

Debugging Tips

  1. Enable Debugging:

    • Use Guzzle’s middleware to log requests:
      $stack = Http\Message\MultipartStream\ServerRequestFactory::createStack();
      $stack->pushMiddleware(new Http\Client\Common\Plugin\LogPlugin(null, true));
      
      $builder = new Gitlab\HttpClient\Builder();
      $builder->setHandler($stack);
      
  2. Common HTTP Errors:

    • 401 Unauthorized: Invalid token or expired token.
    • 403 Forbidden: Insufficient permissions (e.g., project access level).
    • 404 Not Found: Resource does not exist (e.g., project ID mismatch).
  3. Deprecation Warnings:

    • Check the changelog for breaking changes (e.g., PHP 7.2/7.3 dropped in v11.7).

Extension Points

  1. Custom API Endpoints:

    • Extend the client by creating a custom API class:
      use Gitlab\Client;
      use Gitlab\Api;
      
      class CustomApi extends Api
      {
          public function customEndpoint($param)
          {
              return $this->get("api/v4/custom", ['param' => $param]);
          }
      }
      
      $client->setApi(new CustomApi($client));
      
  2. Middleware:

    • Add request/response middleware via HTTPlug plugins:
      $plugin = new class implements Http\Client\Plugin {
          public function __invoke(Callable $handler) {
              return function ($request) use ($handler) {
                  // Modify request
                  $request = $request->withHeader('X-Custom-Header', 'value');
                  return $handler($request);
              };
          }
      };
      $builder->addPlugin($plugin);
      
  3. Caching:

    • Use php-http/cache-plugin for caching responses:
      $cachePlugin = new Http\Cache\Plugin($cachePool);
      $builder->addPlugin($cachePlugin);
      
  4. Testing:

    • Mock the client in tests using Gitlab\Client and Http\Mock\Client:
      $mock = new Http\Mock
      
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.
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
anil/file-picker
broqit/fields-ai