djamy/google-calendar-bundle
Installation:
composer require djamy/google-calendar-bundle:dev-master
Ensure your Laravel project is on Laravel 5.0+ (check composer.json for compatibility).
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);
}
Configuration:
.p12 key file and place it in app/Resources/GoogleCalendarBundle/ (e.g., my-service-account.p12).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',
],
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'));
}
Event Management:
$event = $calendarService->createEvent('primary', [
'summary' => 'Team Meeting',
'start' => new \DateTime('2023-12-25T10:00:00'),
'end' => new \DateTime('2023-12-25T11:00:00'),
]);
$calendarService->updateEvent('event-id', ['summary' => 'Updated Meeting']);
$calendarService->deleteEvent('event-id');
Calendar Listings:
$calendars = $calendarService->listCalendars();
$events = $calendarService->getEvents('calendar-id', [
'timeMin' => new \DateTime('2023-12-01'),
'maxResults' => 10,
]);
Dependency Injection:
Always inject GoogleCalendarService into controllers/services:
public function __construct(GoogleCalendarService $calendarService) {
$this->calendarService = $calendarService;
}
Timezone Handling:
Use \DateTime objects with timezone-aware strings (e.g., '2023-12-25T10:00:00+02:00').
Batch Operations: Loop through events or calendars:
foreach ($calendars as $calendar) {
$events = $calendarService->getEvents($calendar['id']);
// Process events...
}
Authentication Errors:
.p12 file path in parameters.php is correct and accessible (check permissions).client_email matches the service account email in Google Cloud Console..p12 file and update paths if errors like InvalidCredentialsException occur.Timezone Mismatches:
\DateTime objects with explicit timezones:
$event['start'] = new \DateTime('2023-12-25T10:00:00', new \DateTimeZone('Europe/Paris'));
Carbon for easier timezone handling:
use Carbon\Carbon;
$event['start'] = Carbon::parse('2023-12-25 10:00:00')->setTimezone('UTC');
Rate Limits:
cache() helper) to avoid repeated calls:
$events = cache()->remember("events_{$calendarId}", now()->addHours(1), function () use ($calendarService, $calendarId) {
return $calendarService->getEvents($calendarId);
});
Event ID Handling:
createEvent() are Google Calendar-specific (e.g., abc123@google.com). Store these in your database if you need to update/delete later.google_event_id column to your events table.Recurring Events:
RRULE). Use the Google API’s recurrence field manually:
$event['recurrence'] = ['RRULE:FREQ=WEEKLY;BYDAY=MO,WE,FR'];
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.
Test with a Secondary Calendar:
client_email) in Google Calendar settings.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.');
}
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);
}
}
Webhook Integration: Use Google Calendar’s push notifications to sync events in real-time:
POST /google-calendar-webhook.X-Goog-Message-Signature header.Laravel Scheduler: Sync events periodically with Laravel’s scheduler:
// app/Console/Kernel.php
protected function schedule(Schedule $schedule) {
$schedule->call(function () {
$this->syncGoogleEvents();
})->hourly();
}
Testing:
Mock the GoogleCalendarService in PHPUnit:
$mock = $this->createMock(GoogleCalendarService::class);
$mock->method('getEvents')->willReturn([/* mock events */]);
$this->app->instance(GoogleCalendarService::class, $mock);
How can I help you explore Laravel packages today?