Why Integrate Google Calendar API with Laravel?
Scheduling is a critical part of modern business operations. Whether you run a SaaS platform, an eCommerce store, or a service-based business, automating appointment booking, event reminders, and team calendars saves time and reduces manual errors. By connecting your Laravel application to the Google Calendar API, you can programmatically create, read, update, and delete calendar events — giving your users and customers a seamless scheduling experience.
At D&D Technology, we help startups, small businesses, and enterprises build scalable digital solutions with powerful API integrations. This step-by-step guide walks you through the entire process of integrating Google Calendar API into your Laravel app.
What You'll Need Before You Start
Before diving into the code, make sure you have the following prerequisites in place:
- A working Laravel application (Laravel 9 or later recommended)
- A Google account with access to the Google Cloud Console
- Composer installed on your development machine
- Basic understanding of Laravel service providers and middleware
- PHP 8.1 or higher
Step 1: Set Up a Google Cloud Project and Enable the Calendar API
The first step is to create a project in the Google Cloud Console and enable the Google Calendar API:
- Go to the Google Cloud Console and create a new project.
- Navigate to APIs & Services → Library and search for "Google Calendar API."
- Click on the Google Calendar API result and click Enable.
- Go to APIs & Services → Credentials and click Create Credentials → OAuth Client ID.
- Configure the consent screen if prompted. Choose "External" for the user type and fill in the required fields.
- For the application type, select Web Application.
- Add your callback URL (e.g.,
https://yourdomain.com/auth/google/callback) under "Authorized redirect URIs." - Save the Client ID and Client Secret — you'll need them in the next step.
Step 2: Install Laravel Socialite and Google API Client
Laravel Socialite simplifies OAuth authentication, and the Google API Client library handles calendar operations. Install both via Composer:
composer require laravel/socialite
google/apiclient:^2.0Step 3: Configure Environment Variables
Add your Google credentials to the .env file:
GOOGLE_CLIENT_ID=your-client-id
GOOGLE_CLIENT_SECRET=your-client-secret
GOOGLE_REDIRECT_URI=https://yourdomain.com/auth/google/callbackThen, update config/services.php to include the Google configuration:
'google' => [
'client_id' => env('GOOGLE_CLIENT_ID'),
'client_secret' => env('GOOGLE_CLIENT_SECRET'),
'redirect' => env('GOOGLE_REDIRECT_URI'),
],Step 4: Create the Authentication Routes and Controller
Create routes in routes/web.php to handle the OAuth flow:
Route::get('/auth/google', [GoogleCalendarController::class, 'redirectToGoogle']);
Route::get('/auth/google/callback', [GoogleCalendarController::class, 'handleGoogleCallback']);In your controller, use Socialite to handle the redirect and callback:
use Laravel\Socialite\Facades\Socialite;
use Illuminate\Support\Facades\Auth;
public function redirectToGoogle()
{
return Socialite::driver('google')
->scopes(['https://www.googleapis.com/auth/calendar'])
->redirect();
}
public function handleGoogleCallback()
{
$googleUser = Socialite::driver('google')->user();
// Store the token in the database
$user = Auth::user();
$user->google_token = $googleUser->token;
$user->google_refresh_token = $googleUser->refreshToken;
$user->save();
return redirect('/dashboard')->with('success', 'Google Calendar connected successfully!');
}Step 5: Build a Reusable Google Calendar Service Class
To keep your code clean and maintainable, create a dedicated service class for calendar operations:
namespace App\Services;
use Google\Client;
use Google\Service\Calendar;
use Google\Service\Calendar\Event;
class GoogleCalendarService
{
protected $client;
protected $service;
public function __construct($user)
{
$this->client = new Client();
$this->client->setClientId(config('services.google.client_id'));
$this->client->setClientSecret(config('services.google.client_secret'));
$this->client->setAccessToken($user->google_token);
// Refresh token if expired
if ($this->client->isAccessTokenExpired() && $user->google_refresh_token) {
$this->client->fetchAccessTokenWithRefreshToken($user->google_refresh_token);
}
$this->service = new Calendar($this->client);
}
public function createEvent($calendarId, $eventData)
{
$event = new Event([
'summary' => $eventData['summary'],
'description' => $eventData['description'] ?? '',
'start' => ['dateTime' => $eventData['start'], 'timeZone' => 'Asia/Kolkata'],
'end' => ['dateTime' => $eventData['end'], 'timeZone' => 'Asia/Kolkata'],
]);
return $this->service->events->insert($calendarId, $event);
}
public function getEvents($calendarId, $timeMin, $timeMax)
{
$optParams = [
'timeMin' => $timeMin,
'timeMax' => $timeMax,
'singleEvents' => true,
'orderBy' => 'startTime',
];
return $this->service->events->listEvents($calendarId, $optParams);
}
public function updateEvent($calendarId, $eventId, $eventData)
{
$event = $this->service->events->get($calendarId, $eventId);
$event->setSummary($eventData['summary']);
$event->setDescription($eventData['description'] ?? '');
return $this->service->events->update($calendarId, $eventId, $event);
}
public function deleteEvent($calendarId, $eventId)
{
return $this->service->events->delete($calendarId, $eventId);
}
}Step 6: Use the Service in Your Controller
With the service class in place, you can easily perform CRUD operations on calendar events:
use App\Services\GoogleCalendarService;
public function storeEvent(Request $request)
{
$user = Auth::user();
$calendarService = new GoogleCalendarService($user);
$event = $calendarService->createEvent('primary', [
'summary' => $request->input('title'),
'description' => $request->input('description'),
'start' => $request->input('start_time'),
'end' => $request->input('end_time'),
]);
return redirect()->back()->with('success', 'Event created: ' . $event->htmlLink);
}Step 7: Handle Token Refresh and Error Management
Access tokens expire after a short period. Always handle token refresh gracefully and implement proper error handling:
- Store both the
access_tokenandrefresh_tokenin your database. - Check for token expiration before every API call.
- Use try-catch blocks around API operations to handle exceptions.
- Log errors for debugging and notify users when re-authentication is needed.
Best Practices for Google Calendar API Integration
To ensure a reliable and secure integration, follow these best practices:
- Use service accounts for server-to-server communication where user authentication is not required.
- Implement rate limiting to stay within Google API quotas.
- Cache calendar data where appropriate to reduce API calls.
- Always validate and sanitize user input before passing it to the API.
- Use webhooks (push notifications) to get real-time updates instead of polling the API repeatedly.
How D&D Technology Can Help
Building robust API integrations requires experience with authentication flows, error handling, and scalable architecture. At D&D Technology, a leading web development company in Jaipur, we specialize in Laravel development, API integration services, SaaS development, and AI automation for businesses worldwide.
Whether you're a startup building your first SaaS product or an enterprise looking to automate scheduling across teams, our team can design and develop a tailored solution that fits your business needs. We provide end-to-end technology solutions — from planning and UI/UX design to development, testing, deployment, and long-term support.
Contact us for a free consultation and let's discuss how we can help you integrate Google Calendar or any other API into your Laravel application.
Conclusion
Integrating Google Calendar API with your Laravel application opens up powerful automation possibilities for scheduling, event management, and customer engagement. By following this guide, you can set up OAuth 2.0 authentication, manage tokens with Laravel Socialite, and build a reusable service class for all your calendar operations.
The key to a successful integration is clean code, proper error handling, and a scalable architecture. If you need professional assistance, D&D Technology is here to help you build secure, scalable, and growth-focused digital solutions — Design. Develop. Deliver.
Join the Conversation
0 Comments