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 Calendar Bundle Laravel Package

djamy/google-calendar-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require djamy/google-calendar-bundle:dev-master
    

    Ensure your Laravel project is on Laravel 5.0+ (check composer.json for compatibility).

  2. Enable the Bundle: Add to config/app.php under providers:

    Djamy\GoogleCalendarBundle\DjamyGoogleCalendarBundle::class,
    

    And register in AppServiceProvider (or AppKernel.php for older Laravel):

    public function register()
    {
        $this->app->register(Djamy\GoogleCalendarBundle\DjamyGoogleCalendarBundle::class);
    }
    
  3. Configuration:

    • Generate a Service Account in Google Cloud Console (Server-to-Server OAuth).
    • Download the .p12 key file and place it in app/Resources/GoogleCalendarBundle/ (e.g., my-service-account.p12).
    • Update config/parameters.php (or .env for Laravel 5.2+):
      'google_calendar' => [
          'api_key_file' => 'app/Resources/GoogleCalendarBundle/my-service-account.p12',
          'api_url' => 'https://www.googleapis.com/auth/calendar',
          'client_email' => 'your-service-account@project-id.iam.gserviceaccount.com',
      ],
      
  4. First Use Case: Fetch events for a specific calendar in a controller:

    use Djamy\GoogleCalendarBundle\Service\GoogleCalendarService;
    
    public function index(GoogleCalendarService $calendarService)
    {
        $events = $calendarService->getEvents('primary'); // 'primary' or calendar ID
        return view('events.index', compact('events'));
    }
    

Implementation Patterns

Core Workflows

  1. Event Management:

    • Create/Update Events:
      $event = $calendarService->createEvent('primary', [
          'summary' => 'Team Meeting',
          'start' => new \DateTime('2023-12-25T10:00:00'),
          'end' => new \DateTime('2023-12-25T11:00:00'),
      ]);
      
    • Update Event:
      $calendarService->updateEvent('event-id', ['summary' => 'Updated Meeting']);
      
    • Delete Event:
      $calendarService->deleteEvent('event-id');
      
  2. Calendar Listings:

    • List all calendars:
      $calendars = $calendarService->listCalendars();
      
    • Fetch events for a specific calendar:
      $events = $calendarService->getEvents('calendar-id', [
          'timeMin' => new \DateTime('2023-12-01'),
          'maxResults' => 10,
      ]);
      
  3. Dependency Injection: Always inject GoogleCalendarService into controllers/services:

    public function __construct(GoogleCalendarService $calendarService) {
        $this->calendarService = $calendarService;
    }
    
  4. Timezone Handling: Use \DateTime objects with timezone-aware strings (e.g., '2023-12-25T10:00:00+02:00').

  5. Batch Operations: Loop through events or calendars:

    foreach ($calendars as $calendar) {
        $events = $calendarService->getEvents($calendar['id']);
        // Process events...
    }
    

Gotchas and Tips

Common Pitfalls

  1. Authentication Errors:

    • Ensure the .p12 file path in parameters.php is correct and accessible (check permissions).
    • Verify the client_email matches the service account email in Google Cloud Console.
    • Fix: Re-download the .p12 file and update paths if errors like InvalidCredentialsException occur.
  2. Timezone Mismatches:

    • Google Calendar uses UTC by default. Pass \DateTime objects with explicit timezones:
      $event['start'] = new \DateTime('2023-12-25T10:00:00', new \DateTimeZone('Europe/Paris'));
      
    • Tip: Use Laravel’s Carbon for easier timezone handling:
      use Carbon\Carbon;
      $event['start'] = Carbon::parse('2023-12-25 10:00:00')->setTimezone('UTC');
      
  3. Rate Limits:

    • Google API has quotas. Monitor usage in Google Cloud Console.
    • Tip: Cache responses (e.g., with Laravel’s cache() helper) to avoid repeated calls:
      $events = cache()->remember("events_{$calendarId}", now()->addHours(1), function () use ($calendarService, $calendarId) {
          return $calendarService->getEvents($calendarId);
      });
      
  4. Event ID Handling:

    • Event IDs returned by createEvent() are Google Calendar-specific (e.g., abc123@google.com). Store these in your database if you need to update/delete later.
    • Tip: Add a google_event_id column to your events table.
  5. Recurring Events:

    • The bundle does not natively support recurring events (e.g., RRULE). Use the Google API’s recurrence field manually:
      $event['recurrence'] = ['RRULE:FREQ=WEEKLY;BYDAY=MO,WE,FR'];
      

Debugging Tips

  1. Enable API Logging: Add this to config/parameters.php to log API responses:

    'google_calendar' => [
        'debug' => true, // Enable debug mode
        // ... other config
    ],
    

    Check storage/logs/laravel.log for detailed API calls/responses.

  2. Test with a Secondary Calendar:

    • Use a test calendar (not your primary) during development to avoid accidental deletions.
    • Share the test calendar with your service account email (client_email) in Google Calendar settings.
  3. Handle Exceptions: Wrap API calls in try-catch blocks:

    try {
        $events = $calendarService->getEvents('primary');
    } catch (\Google\Service\Exception $e) {
        Log::error('Google Calendar API Error: ' . $e->getMessage());
        return back()->with('error', 'Failed to fetch events.');
    }
    

Extension Points

  1. Custom Event Fields: Extend the bundle by creating a custom service that wraps GoogleCalendarService:

    class CustomCalendarService {
        public function __construct(GoogleCalendarService $calendarService) {
            $this->calendarService = $calendarService;
        }
    
        public function createCustomEvent(array $data) {
            $eventData = [
                'summary' => $data['title'],
                'description' => $data['description'] ?? '',
                'start' => new \DateTime($data['start']),
                'end' => new \DateTime($data['end']),
                'custom_field' => $data['custom_field'] // Your extension
            ];
            return $this->calendarService->createEvent('primary', $eventData);
        }
    }
    
  2. Webhook Integration: Use Google Calendar’s push notifications to sync events in real-time:

    • Set up a Laravel route to handle POST /google-calendar-webhook.
    • Verify the request signature using the X-Goog-Message-Signature header.
  3. Laravel Scheduler: Sync events periodically with Laravel’s scheduler:

    // app/Console/Kernel.php
    protected function schedule(Schedule $schedule) {
        $schedule->call(function () {
            $this->syncGoogleEvents();
        })->hourly();
    }
    
  4. Testing: Mock the GoogleCalendarService in PHPUnit:

    $mock = $this->createMock(GoogleCalendarService::class);
    $mock->method('getEvents')->willReturn([/* mock events */]);
    $this->app->instance(GoogleCalendarService::class, $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.
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
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