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 Api Laravel Package

tomshaw/google-api

Laravel Google OAuth 2.0 service client with configurable token storage (DB or custom), published config, and migrations. Integrates google/apiclient-services and supports Composer cleanup to include only the Google APIs you need (e.g., Gmail, Calendar).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:

    composer require tomshaw/google-api
    

    Add this to composer.json to reduce bundle size:

    "extra": {
        "google/apiclient-services": ["Gmail", "Calendar"]
    }
    
  2. Publish config:

    php artisan vendor:publish --provider="TomShaw\GoogleApi\Providers\GoogleApiServiceProvider" --tag=config
    

    Configure config/google-api.php with:

    • auth_config: Path to your Google OAuth credentials JSON.
    • service_scopes: Required scopes (e.g., ['https://www.googleapis.com/auth/calendar']).
  3. Run migrations (if using database storage):

    php artisan migrate
    

First Use Case: OAuth Flow

use TomShaw\GoogleApi\GoogleClient;

// Redirect user to Google OAuth
$authUrl = $client->createAuthUrl();
return redirect($authUrl);

// Handle callback
$authCode = $request->get('code');
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);

Implementation Patterns

Dependency Injection

Use Laravel’s DI container to inject GoogleClient or service adapters:

public function __construct(
    private GoogleClient $client,
    private GoogleCalendar $calendar
) {}

Service Adapters

Leverage built-in adapters for common APIs:

// Calendar
$events = $calendar->listEvents();
$event = $calendar->createEvent(['summary' => 'Meeting']);

// Gmail (with Laravel Mailable)
$mailable = new SendGmailMail($user);
$gmail = new GoogleGmail($client);
$gmail->send($mailable);

Token Management

  • Refresh tokens automatically:
    $client->refreshAccessToken();
    
  • Custom storage: Implement StorageAdapterInterface for Redis/Redis:
    'token_storage_adapter' => App\Services\RedisTokenStorage::class,
    

Workflow: Sync Google Calendar to Database

public function syncCalendar(GoogleCalendar $calendar) {
    $events = $calendar->listEvents();
    foreach ($events as $event) {
        Event::updateOrCreate(
            ['google_id' => $event->id],
            ['title' => $event->summary]
        );
    }
}

Gotchas and Tips

Common Pitfalls

  1. Scopes: Ensure service_scopes in config matches the API’s requirements. Missing scopes cause 403 errors.
  2. Token Expiry: Always handle Google_Auth_Exception for expired tokens:
    try {
        $client->refreshAccessToken();
    } catch (\Google_Auth_Exception $e) {
        // Redirect to OAuth flow
    }
    
  3. Service Loading: Only load required services in composer.json to avoid bloating the vendor directory.

Debugging

  • Enable API logging:
    $client->setDeveloperKey('YOUR_KEY'); // For API calls
    $client->setLogLevel(\Google_Client::LOG_DEBUG);
    
  • Check token storage: Verify token_storage_adapter is correctly configured (e.g., database/Redis).

Extension Points

  1. Custom Adapters: Extend GoogleApiService for unsupported APIs:
    class GoogleSheets extends GoogleApiService {
        protected $serviceName = 'sheets';
        // Add custom methods
    }
    
  2. Middleware: Use Laravel middleware to validate tokens:
    public function handle(Request $request, Closure $next) {
        if (!$request->user()->hasGoogleToken()) {
            return redirect()->route('google.auth');
        }
        return $next($request);
    }
    
  3. Batch Operations: Use Google_Service_Resource methods for bulk operations (e.g., users.batchGet in Admin SDK).

Performance Tips

  • Cache API responses: Use Laravel’s cache for rate-limited endpoints:
    $events = Cache::remember("google_events_{$userId}", now()->addHours(1), function() use ($calendar) {
        return $calendar->listEvents();
    });
    
  • Lazy-load services: Initialize adapters only when needed:
    $drive = app(GoogleDrive::class)->onlyIf(function() {
        return request()->has('drive_action');
    });
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity