
laravel-queue-patterns
Best practices for Laravel queues including job structure, batching, chaining, middleware, retry strategies, and error handling.
- Installs
- 96
- Last 24h
- —
- Trending rank
- —
- Security
- Not audited
Install
Works with every agent the skills CLI supports.
npx skills add https://github.com/iserter/laravel-claude-agents --skill laravel-queue-patterns- 01
Install
Run the command in your project. The CLI asks which agents to install for.
- 02
Describe the task
Ask your agent for something this skill covers. It loads laravel-queue-patterns automatically when relevant.
- 03
Review the result
The agent follows the SKILL.md steps, scripts and references bundled with the skill.
SKILL.md
The instructions your agent reads when the skill is triggered.
Laravel Queue Patterns
Job Structure
<?php
namespace App\Jobs;
use App\Models\Order;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class ProcessOrder implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(
public readonly Order $order,
) {}
public function handle(PaymentGateway $gateway): void
{
$gateway->charge($this->order);
$this->order->update(['status' => 'processed']);
}
public function failed(\Throwable $exception): void
{
$this->order->update(['status' => 'failed']);
// Notify admin, log, etc.
}
}
Dispatch Patterns
// ✅ Standard dispatch
ProcessOrder::dispatch($order);
// ✅ Dispatch to specific queue/connection
ProcessOrder::dispatch($order)
->onQueue('payments')
->onConnection('redis');
// ✅ Delayed dispatch
ProcessOrder::dispatch($order)->delay(now()->addMinutes(5));
// ✅ Conditional dispatch
ProcessOrder::dispatchIf($order->isPaid(), $order);
ProcessOrder::dispatchUnless($order->isCancelled(), $order);
// ✅ Dispatch after database transaction commits
ProcessOrder::dispatch($order)->afterCommit();
// ❌ Dispatching inside a transaction without afterCommit
DB::transaction(function () use ($order) {
$order->save();
ProcessOrder::dispatch($order); // Job may run before commit
});
// ✅ Safe inside transactions
DB::transaction(function () use ($order) {
$order->save();
ProcessOrder::dispatch($order)->afterCommit();
});
Job Middleware
use Illuminate\Queue\Middleware\RateLimited;
use Illuminate\Queue\Middleware\ThrottlesExceptions;
use Illuminate\Queue\Middleware\WithoutOverlapping;
class ProcessOrder implements ShouldQueue
{
public function middleware(): array
{
return [
// Rate limit to 10 jobs per minute
new RateLimited('orders'),
// Prevent overlapping by order ID
(new WithoutOverlapping($this->order->id))
->releaseAfter(60)
->expireAfter(300),
// Throttle on exceptions - wait 5 min after 3 exceptions
(new ThrottlesExceptions(3, 5))
->backoff(5),
];
}
}
// Define rate limiter in AppServiceProvider
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;
RateLimiter::for('orders', function ($job) {
return Limit::perMinute(10);
});
Job Chaining
use Illuminate\Support\Facades\Bus;
// ✅ Sequential execution - next job runs only if previous succeeds
Bus::chain([
new ValidateOrder($order),
new ChargePayment($order),
new SendConfirmation($order),
new UpdateInventory($order),
])->onQueue('orders')->dispatch();
// ✅ With catch callback
Bus::chain([
new ValidateOrder($order),
new ChargePayment($order),
])->catch(function (\Throwable $e) use ($order) {
$order->update(['status' => 'failed']);
})->dispatch();
Job Batching
use Illuminate\Bus\Batch;
use Illuminate\Support\Facades\Bus;
$batch = Bus::batch([
new ProcessCsvChunk($file, 0, 1000),
new ProcessCsvChunk($file, 1000, 2000),
new ProcessCsvChunk($file, 2000, 3000),
])
->then(function (Batch $batch) {
// All jobs completed successfully
Notification::send($user, new ImportComplete());
})
->catch(function (Batch $batch, \Throwable $e) {
// First batch job failure detected
})
->finally(function (Batch $batch) {
// Batch finished (success or failure)
Storage::delete($file);
})
->name('CSV Import')
->onQueue('imports')
->allowFailures()
->dispatch();
// Check batch progress
$batch = Bus::findBatch($batchId);
echo $batch->progress(); // Percentage complete
Jobs in a batch must use the Illuminate\Bus\Batchable trait.
Unique Jobs
use Illuminate\Contracts\Queue\ShouldBeUnique;
class RecalculateReport implements ShouldQueue, ShouldBeUnique
{
public function __construct(
public readonly int $reportId,
) {}
// Unique for 1 hour
public int $uniqueFor = 3600;
// Custom unique ID
public function uniqueId(): string
{
return (string) $this->reportId;
}
}
Retry Strategies
class ProcessWebhook implements ShouldQueue
{
// ✅ Fixed number of attempts
public int $tries = 5;
// ✅ Or retry until a time limit
public function retryUntil(): \DateTime
{
return now()->addHours(2);
}
// ✅ Max exceptions before marking failed (allows manual releases)
public int $maxExceptions = 3;
// ✅ Exponential backoff (seconds between retries)
public array $backoff = [10, 60, 300]; // 10s, 1m, 5m
// ✅ Timeout per attempt
public int $timeout = 120;
public function handle(): void
{
// If an unrecoverable error occurs, fail immediately
if ($this->isInvalid()) {
$this->fail('Invalid webhook payload.');
return;
}
// Process...
}
}
Idempotency Patterns
class ChargePayment implements ShouldQueue
{
public function handle(PaymentGateway $gateway): void
{
// ✅ Check if already processed before acting
if ($this->order->payment_id) {
return; // Already charged, skip
}
$payment = $gateway->charge($this->order->total);
// ✅ Use atomic update to prevent double processing
$affected = Order::where('id', $this->order->id)
->whereNull('payment_id')
->update(['payment_id' => $payment->id]);
if ($affected === 0) {
return; // Another worker already processed this
}
}
}
Testing Queues
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Queue;
// ✅ Assert job was dispatched
public function test_order_dispatches_processing_job(): void
{
Queue::fake();
$order = Order::factory()->create();
$order->process();
Queue::assertPushed(ProcessOrder::class, function ($job) use ($order) {
return $job->order->id === $order->id;
});
}
// ✅ Assert chain
public function test_order_dispatches_chain(): void
{
Bus::fake();
$order = Order::factory()->create();
$order->fulfill();
Bus::assertChained([
ValidateOrder::class,
ChargePayment::class,
SendConfirmation::class,
]);
}
// ✅ Assert batch
public function test_import_dispatches_batch(): void
{
Bus::fake();
(new CsvImporter)->import($file);
Bus::assertBatched(function ($batch) {
return $batch->jobs->count() === 3
&& $batch->jobs->every(fn ($job) => $job instanceof ProcessCsvChunk);
});
}
// ✅ Execute job to test handler logic
public function test_process_order_charges_payment(): void
{
$order = Order::factory()->create();
ProcessOrder::dispatchSync($order);
$this->assertNotNull($order->fresh()->payment_id);
}
Checklist
- Jobs implement ShouldQueue and use standard traits
- Jobs accept only serializable data (models, primitives)
- Retry strategy configured ($tries, $backoff, retryUntil)
- failed() method handles cleanup and notifications
- afterCommit() used when dispatching inside transactions
- Job middleware used for rate limiting and overlap prevention
- Chains used for sequential dependent operations
- Batches used for parallel independent operations
- Jobs are idempotent (safe to run multiple times)
- ShouldBeUnique used to prevent duplicate jobs
- Queue and Bus fakes used in tests
FAQ
What does the laravel-queue-patterns skill do?
Best practices for Laravel queues including job structure, batching, chaining, middleware, retry strategies, and error handling.
How do I install laravel-queue-patterns?
Run npx skills add https://github.com/iserter/laravel-claude-agents --skill laravel-queue-patterns in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/laravel-queue-patterns/ (personal) or .claude/skills/laravel-queue-patterns/ (project).
Which AI agents can use laravel-queue-patterns?
Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.
Is laravel-queue-patterns safe to install?
No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.
Who maintains laravel-queue-patterns?
It is published by iserter in iserter/laravel-claude-agents. It has 96 recorded installs.
More from iserter/laravel-claude-agents
eloquent-best-practices
iserter/laravel-claude-agents
Best practices for Laravel Eloquent ORM including query optimization, relationship management, and avoiding common pitfalls like N+1 queries.
laravel-tdd
iserter/laravel-claude-agents
Open the skill to read its SKILL.md instructions.
laravel-blade-component-patterns
iserter/laravel-claude-agents
Open the skill to read its SKILL.md instructions.
api-resource-patterns
iserter/laravel-claude-agents
Open the skill to read its SKILL.md instructions.
laravel-systematic-debugging
iserter/laravel-claude-agents
Open the skill to read its SKILL.md instructions.
laravel-validation-patterns
iserter/laravel-claude-agents
Open the skill to read its SKILL.md instructions.
Popular backend & apis skills
find-skills
vercel-labs/skills
Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.
entra-app-registration
microsoft/azure-skills
Guides Microsoft Entra ID app registration, OAuth 2.0 authentication, and MSAL integration. USE FOR: create app registration, register Azure AD app, configure OAuth, set up authentication, add API permissions, generate service principal, MSAL example, console app auth, Entra ID setup, Azure AD authentication. DO NOT USE FOR: Key Vault secrets (use azure-keyvault-expiration-audit), general Azure resource security guidance.
google-agents-cli-adk-code
google/agents-cli
This skill should be used when the user wants to "write agent code", "build an agent with ADK", "add a tool", "create a callback", "define an agent", "use state management" — in a project that needs ADK (Agent Development Kit) API patterns and code examples. It provides a quick reference for agent types, tool definitions, orchestration patterns, callbacks, state management, the graph Workflow API, and reference recipes to study. Do NOT use for scaffolding (use google-agents-cli-scaffold) or deployment (use google-agents-cli-deploy).
embedded-captions
heygen-com/hyperframes
Add captions or subtitles to an existing single-subject talking-head video without editing the footage. Use for plain verbatim captions, cinematic captions embedded behind the subject, VFX captions, “炸/特效/酷炫字幕,” or a named identity from the 35-style catalog. Route by visual identity, not by backend engine. The quiet anchor rail is the default; embed every word only when the user explicitly wants a fully cinematic treatment. The workflow runs locally end to end, including transcription and subject matting; split multi-shot footage before applying it.
entra-agent-id
microsoft/azure-skills
Provision Microsoft Entra Agent Identity Blueprints, BlueprintPrincipals, and per-instance Agent Identities via Microsoft Graph, and configure OAuth 2.0 token exchange (fmipath, OBO, cross-tenant) including the Microsoft Entra SDK for AgentID sidecar. USE FOR: Agent Identity Blueprint, BlueprintPrincipal, agent OAuth, fmipath token exchange, agent OBO, Workload Identity Federation for agents, polyglot agent auth, Microsoft.Identity.Web.AgentIdentities. DO NOT USE FOR: standard Entra app registration (use entra-app-registration), Microsoft Foundry agent authoring (use microsoft-foundry).
neon
neondatabase/agent-skills
Overview of Neon, a complete set of cloud backend primitives around Lakebase Postgres: Auth, Object Storage, Functions, the AI Gateway, and Realtime. Start here to choose Neon for undecided login, files, APIs, and LLM calls, set up the CLI or MCP server, and follow the branch-first workflow. Use when building an app or backend on Neon, or when "Neon" or "Lakebase Postgres" is mentioned. Child skill neon-postgres wins for an existing DATABASEURL, SQL, schema, inspect, or search. Child skill neon-auth wins for login, users, sessions, identity routing, and Managed Better Auth setup. Child skill neon-realtime wins for live queries in reactive apps and agents. Also use for object storage, S3, buckets, serverless functions, function triggers, cron, AI gateway, LLM calls, realtime, logs, Loki, Grafana, observability, postgres, database, backend, Claimable Neon, neon.new, or a no-signup database.