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

Google Apiclient Laravel Package

pulkitjalan/google-apiclient

Laravel package to integrate Google APIs via the official Google API PHP Client. Provides a simple service provider, facade, and config for authentication and common Google services, making it easy to access Google APIs in your Laravel apps.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require pulkitjalan/google-apiclient
    

    Publish the config file (if available):

    php artisan vendor:publish --provider="PulkitJalan\GoogleApiClient\GoogleApiClientServiceProvider"
    
  2. First Use Case: Authenticating with Google APIs Configure credentials in .env:

    GOOGLE_CLIENT_ID=your_client_id
    GOOGLE_CLIENT_SECRET=your_client_secret
    GOOGLE_REDIRECT_URI=http://your-app.dev/auth/google/callback
    GOOGLE_SCOPES="https://www.googleapis.com/auth/drive.readonly"
    

    Initialize the client in a controller or service:

    use PulkitJalan\GoogleApiClient\Facades\GoogleApiClient;
    
    public function authenticate()
    {
        $client = GoogleApiClient::getClient();
        $authUrl = $client->createAuthUrl();
        return redirect()->to($authUrl);
    }
    
  3. Callback Handling Add a route for the OAuth callback:

    Route::get('/auth/google/callback', [AuthController::class, 'handleCallback']);
    

    Process the callback in your controller:

    public function handleCallback()
    {
        $client = GoogleApiClient::getClient();
        $accessToken = $client->authenticate($_GET['code']);
        // Store token in DB or session
    }
    

Implementation Patterns

Common Workflows

1. Service Layer Integration

Create a dedicated service class to abstract API interactions:

namespace App\Services;

use PulkitJalan\GoogleApiClient\Facades\GoogleApiClient;

class GoogleDriveService
{
    protected $client;

    public function __construct()
    {
        $this->client = GoogleApiClient::getClient();
    }

    public function listFiles()
    {
        $service = new \Google_Service_Drive($this->client);
        $results = $service->files->listFiles();
        return $results->getFiles();
    }
}

2. Middleware for Authenticated Requests

Use middleware to ensure the Google client is authenticated:

namespace App\Http\Middleware;

use Closure;
use PulkitJalan\GoogleApiClient\Facades\GoogleApiClient;

class EnsureGoogleAuth
{
    public function handle($request, Closure $next)
    {
        $client = GoogleApiClient::getClient();
        if (!$client->isAccessTokenValid()) {
            return redirect()->route('google.auth');
        }
        return $next($request);
    }
}

3. Batch Operations

Leverage the client for batch requests (e.g., Drive API):

public function batchUpdateFiles($fileIds, $newNames)
{
    $service = new \Google_Service_Drive($this->client);
    $batch = $service->createBatch();
    foreach ($fileIds as $index => $fileId) {
        $batch->add(
            $service->files->update($fileId, ['name' => $newNames[$index]])
        );
    }
    $results = $batch->execute();
    return $results;
}

4. Event-Driven Updates

Use Laravel events to trigger Google API actions (e.g., syncing data on model updates):

// In a model observer or event listener
event(new FileUploaded($file));
// Listener
public function handle(FileUploaded $event)
{
    $service = new \Google_Service_Drive(GoogleApiClient::getClient());
    $fileMetadata = new \Google_Service_Drive_DriveFile([
        'name' => $event->file->name,
        'parents' => [$event->file->folderId]
    ]);
    $file = $service->files->create($fileMetadata, [
        'data' => file_get_contents($event->file->path),
        'uploadType' => 'media',
        'fields' => 'id'
    ]);
}

Integration Tips

Laravel Scout Integration

Use the Google Drive API as a Scout engine for full-text search:

namespace App\Scout;

use PulkitJalan\GoogleApiClient\Facades\GoogleApiClient;
use Laravel\Scout\Builder;

class GoogleDriveEngine extends \Laravel\Scout\Engine
{
    public function search($query)
    {
        $service = new \Google_Service_Drive(GoogleApiClient::getClient());
        $results = $service->files->listFiles([
            'q' => "name contains '$query'",
            'fields' => 'files(id, name)'
        ]);
        return $results->getFiles();
    }
}

Queue Jobs for API Calls

Offload long-running API operations to queues:

namespace App\Jobs;

use PulkitJalan\GoogleApiClient\Facades\GoogleApiClient;
use Illuminate\Bus\Queueable;

class SyncGoogleDrive implements Queueable
{
    public function handle()
    {
        $service = new \Google_Service_Drive(GoogleApiClient::getClient());
        // Process files asynchronously
    }
}

Caching API Responses

Cache frequent API calls to reduce rate limits:

public function getUserData($userId)
{
    return Cache::remember("google_user_{$userId}", now()->addHours(1), function () use ($userId) {
        $service = new \Google_Service_Admin(GoogleApiClient::getClient());
        return $service->directory()->users->get($userId);
    });
}

Gotchas and Tips

Pitfalls

1. Token Expiry Handling

  • Issue: Access tokens expire (typically 1 hour). Refresh tokens may also expire if not used for 6 months.
  • Fix: Implement token refresh logic in a middleware or service:
    public function ensureValidToken()
    {
        $client = GoogleApiClient::getClient();
        if (!$client->isAccessTokenValid()) {
            if ($client->isRefreshTokenValid()) {
                $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
            } else {
                throw new \Exception("No valid tokens available.");
            }
        }
    }
    

2. Rate Limiting

  • Issue: Google APIs enforce rate limits (e.g., 1,000 requests per 100 seconds for Drive API).
  • Fix: Implement exponential backoff or use Laravel's throttle middleware:
    Route::middleware(['throttle:100,1'])->group(function () {
        // Rate-limited routes
    });
    

3. Scopes and Permissions

  • Issue: Requesting unnecessary scopes can lead to rejected OAuth requests.
  • Fix: Scope down to only what’s needed:
    GOOGLE_SCOPES="https://www.googleapis.com/auth/drive.metadata.readonly"
    

4. Service Account Quirks

  • Issue: Service accounts (for server-to-server auth) require explicit delegation or domain-wide delegation.
  • Fix: Enable the Google Workspace domain-wide delegation in the Admin Console and use the service_account_name config:
    GOOGLE_SERVICE_ACCOUNT_NAME=your-service-account@project.iam.gserviceaccount.com
    GOOGLE_KEY_FILE=/path/to/service-account-key.json
    

5. Deprecation Warnings

  • Issue: The underlying google/apiclient library may have breaking changes.
  • Fix: Pin the google/apiclient version in composer.json:
    "require": {
        "google/apiclient": "^2.0"
    }
    

Debugging Tips

1. Enable API Logging

Configure the client to log requests/responses:

$client = GoogleApiClient::getClient();
$client->setDeveloperKey('your-api-key');
$client->setApplicationName('Your App');
$client->setUseBatch(true);
$client->setUseObjects(true);
$client->setDeveloperKeyLogLevel('LOG_DEBUG');

2. Validate OAuth Flow

  • Ensure GOOGLE_REDIRECT_URI matches the URI registered in the Google Cloud Console.
  • Test the OAuth flow locally using ngrok to expose your callback URL:
    ngrok http 8000
    

3. Inspect API Responses

Use dd() or Log::debug() to inspect raw responses:

$response = $service->files->listFiles();
Log::debug($response->getFiles());

4. Handle Quotas Exceeded

Catch Google_Service_Exception with quota-related messages:

try {
    $results = $service->files->listFiles();
} catch (\Google
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
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