richan-fongdasen/laravel-gcr-worker
Installation
composer require richan-fongdasen/laravel-gcr-worker
php artisan vendor:publish --provider="RichanFongdasen\LaravelGcrWorker\GcrWorkerServiceProvider" --tag="config"
Publish the config file to adjust default settings (e.g., config/gcr-worker.php).
Configure Environment
Add Google Cloud credentials to .env:
GCR_WORKER_PROJECT_ID=your-project-id
GCR_WORKER_SERVICE_ACCOUNT=your-service-account@project-id.iam.gserviceaccount.com
GCR_WORKER_REGION=us-central1
Define a Job
Create a job class extending GcrWorkerJob:
use RichanFongdasen\LaravelGcrWorker\Jobs\GcrWorkerJob;
class ProcessPayment extends GcrWorkerJob
{
public function handle()
{
// Your logic here (e.g., process payment via Google Cloud Run)
}
}
Trigger the Job Dispatch the job via CLI or HTTP endpoint:
php artisan gcr-worker:dispatch ProcessPayment --data='{"user_id": 123}'
Or via HTTP (if configured):
curl -X POST http://your-app.test/api/gcr-worker/process-payment
Use this package to offload CPU-intensive or long-running tasks (e.g., PDF generation, API polling) to Google Cloud Run. Example:
// In a controller or command
ProcessPayment::dispatch(['user_id' => 123, 'amount' => 100]);
The job will execute in a separate Cloud Run instance, freeing up your main app.
php artisan gcr-worker:dispatch for manual testing or cron-triggered jobs./api/gcr-worker/{job}) to trigger jobs via HTTP. Protect with middleware (e.g., auth:api).
Route::post('/api/gcr-worker/{job}', [GcrWorkerController::class, 'dispatch']);
ProcessPayment::dispatch()->onQueue('gcr');
json_encode() for complex objects:
$data = ['user' => User::find(1)->toArray()];
ProcessPayment::dispatch($data);
.env or inject them into the job’s handle() method.retryUntil() in your job for transient failures:
public function retryUntil()
{
return now()->addMinutes(5); // Retry for 5 minutes
}
monolog):
\Log::error('Payment failed', ['data' => $this->data]);
config/gcr-worker.php:
'endpoint' => 'https://your-custom-url.run.app',
max_instances in Cloud Run settings to control parallel jobs.GcrWorkerJob facade to mock Cloud Run responses:
$job = new ProcessPayment(['user_id' => 1]);
$job->shouldReceive('handle')->once();
$job->handle();
Http::fake():
$response = Http::post('/api/gcr-worker/process-payment');
$response->assertStatus(202);
Cold Starts:
--min-instances=1) in Cloud Run config to keep instances warm.Payload Size Limits:
Authentication:
roles/run.invoker on the Cloud Run service.gcloud:
gcloud projects add-iam-policy-binding YOUR_PROJECT_ID \
--member="serviceAccount:YOUR_SERVICE_ACCOUNT" \
--role="roles/run.invoker"
Job Timeouts:
Laravel Caching:
Cache::forget() or disable caching for the job.Logs:
gcloud logging read "resource.type=cloud_run_revision" --limit 50
gcloud logging read "resource.type=cloud_run_revision" --limit=1 --follow
Local Debugging:
XDEBUG_CONFIG to debug Cloud Run jobs locally:
XDEBUG_CONFIG="remote_host=host.docker.internal remote_port=9003"
php artisan gcr-worker:debug.Environment Mismatches:
.env variables match between local and Cloud Run. Use php artisan config:clear if needed.Custom Job Middleware: Add middleware to jobs (e.g., for validation or auth):
class ValidatePaymentData
{
public function handle(GcrWorkerJob $job, Closure $next)
{
if (empty($job->data['user_id'])) {
throw new \InvalidArgumentException('User ID required');
}
return $next($job);
}
}
Register in AppServiceProvider:
GcrWorkerJob::addMiddleware(ValidatePaymentData::class);
Webhook Triggers: Extend the package to listen for Pub/Sub or other webhooks:
use RichanFongdasen\LaravelGcrWorker\Jobs\WebhookJob;
class HandleStripeWebhook extends WebhookJob
{
protected $event = 'stripe.payment_succeeded';
}
Monitoring:
Integrate with Cloud Monitoring or third-party tools (e.g., Sentry) by extending the job’s handle():
public function handle()
{
try {
// Job logic
Sentry::captureMessage('Job completed');
} catch (\Exception $e) {
Sentry::captureException($e);
throw $e;
}
}
Batch Processing: Process multiple records in a single job:
class ProcessUserPayments extends GcrWorkerJob
{
public function handle()
{
User::where('needs_payment', true)
->chunk(100, function ($users) {
foreach ($users as $user) {
// Process each user
}
});
}
}
Lazy Loading:
Use lazy() for large datasets to reduce memory usage:
User::where('active', true)->lazy()->each(function ($user) {
// Process user
});
Cron Jobs: Schedule jobs via Cloud Scheduler + Cloud Run:
gcloud scheduler jobs create http process-payments \
--schedule="0 9 * * *" \
--uri="https://your-service.run.app/api/gcr-worker/process-payments" \
--http-method=POST
How can I help you explore Laravel packages today?