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.
Installation
composer require pulkitjalan/google-apiclient
Publish the config file (if available):
php artisan vendor:publish --provider="PulkitJalan\GoogleApiClient\GoogleApiClientServiceProvider"
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);
}
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
}
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();
}
}
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);
}
}
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;
}
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'
]);
}
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();
}
}
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
}
}
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);
});
}
public function ensureValidToken()
{
$client = GoogleApiClient::getClient();
if (!$client->isAccessTokenValid()) {
if ($client->isRefreshTokenValid()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
throw new \Exception("No valid tokens available.");
}
}
}
throttle middleware:
Route::middleware(['throttle:100,1'])->group(function () {
// Rate-limited routes
});
GOOGLE_SCOPES="https://www.googleapis.com/auth/drive.metadata.readonly"
service_account_name config:
GOOGLE_SERVICE_ACCOUNT_NAME=your-service-account@project.iam.gserviceaccount.com
GOOGLE_KEY_FILE=/path/to/service-account-key.json
google/apiclient library may have breaking changes.google/apiclient version in composer.json:
"require": {
"google/apiclient": "^2.0"
}
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');
GOOGLE_REDIRECT_URI matches the URI registered in the Google Cloud Console.ngrok to expose your callback URL:
ngrok http 8000
Use dd() or Log::debug() to inspect raw responses:
$response = $service->files->listFiles();
Log::debug($response->getFiles());
Catch Google_Service_Exception with quota-related messages:
try {
$results = $service->files->listFiles();
} catch (\Google
How can I help you explore Laravel packages today?