Complete AI prompt library for Laravel developers. Covers Eloquent ORM, API Resources, Sanctum/Passport authentication, queues & jobs, Laravel Octane, Pest testing, and production deployment with Forge/Vapor — all with production-ready prompts.
Laravel in 2026: The PHP Framework for Web Artisans
Laravel 11 continues to be the most productive PHP framework — elegant syntax, powerful ORM, built-in queues, and a mature ecosystem. AI can dramatically accelerate Laravel development, but you need to specify modern patterns: Laravel 11's slim structure, Pest for testing, and Livewire or Inertia for full-stack if applicable. These prompts produce code that follows Laravel's conventions and passes a senior PHP developer's code review.
1. API Controller with Form Requests & Resources
You are a senior Laravel 11 developer.
Build a complete API controller for the Task resource following Laravel best practices:
Files to generate:
- app/Http/Controllers/Api/V1/TaskController.php
- app/Http/Requests/Task/CreateTaskRequest.php
- app/Http/Requests/Task/UpdateTaskRequest.php
- app/Http/Resources/TaskResource.php
- app/Http/Resources/TaskCollection.php
- routes/api.php registration
Controller requirements:
- Route model binding with tenancy scope (Task must belong to auth user's organization)
- All write actions authorised via TaskPolicy
- Pagination: 25 per page default, configurable via ?per_page= (max 100)
- Response: TaskResource::collection() with pagination metadata
Form Request validation (CreateTaskRequest):
- authorize(): check user can create tasks in the project
- rules(): title required|min:3|max:255, priority in:low,medium,high,critical, due_at date|after:today
- messages(): custom human-readable error messages
TaskResource:
- Include: id, title, status, priority, due_at (formatted), assignee (nested UserResource), project_id
- Conditionally include: comments count (whenCounted), full description (when requested via ?include=description)
Use PHP 8.3 readonly properties and constructor promotion where appropriate.
2. Eloquent Models with Relationships & Scopes
You are an Eloquent ORM expert.
Design Eloquent models for a multi-tenant project management system:
Models: Organization, User, Project, Task, Comment
Task model requirements:
- SoftDeletes trait
- HasFactory trait with TaskFactory
- Casts: status → TaskStatus enum (PHP 8.1 backed enum), priority → PriorityEnum, due_at → datetime, custom_fields → array
- Relationships: belongsTo(Project), belongsTo(User, 'assigned_to'), hasMany(Comment), belongsTo(Organization)
- Local scopes: scopeOverdue(), scopeAssignedTo(User), scopeForOrganization(Organization), scopeWithStatus(TaskStatus)
- Global scope: OrganizationScope — automatically filters all queries to current tenant
- Accessors: isOverdue (bool), daysUntilDue (int|null) using Attribute::make()
Organization trait (add to all tenant models):
- Boot method: addGlobalScope(OrganizationScope::class)
- Static method: withoutTenantScope() for admin queries
Factory:
- States: overdue(), highPriority(), completed(), assignedTo(User $user)
Output: Task model, TaskStatus enum, OrganizationScope, TaskFactory with states.
3. Sanctum API Authentication
You are a Laravel Sanctum expert.
Implement Sanctum token authentication for a Laravel 11 API:
AuthController endpoints:
- POST /api/auth/login: validate credentials, issue named token (scoped abilities), return token + user
- POST /api/auth/logout: revoke current token
- POST /api/auth/refresh: revoke current, issue new token (token rotation)
- GET /api/auth/me: return authenticated user with organisation
Token abilities (scopes):
- read — GET endpoints only
- write — POST/PUT/PATCH
- admin — DELETE and admin endpoints
- Grant based on user role at login
Rate limiting:
- LoginThrottle middleware: 5 attempts per minute per IP
- Return 429 with Retry-After header
Security:
- Timing-safe password comparison (Hash::check is already timing-safe in Laravel)
- No user enumeration: identical 401 response for wrong email or password
- Log login events: user_id, ip_address, user_agent, success boolean, timestamp
Token expiration:
- Set expiration via Sanctum config: 'expiration' => 60 (minutes)
- Prune expired tokens: schedule('sanctum:prune-expired --hours=24')->daily()
Output: AuthController, LoginRequest, AuthService, and API route registration.
4. Queue Jobs & Events
You are a Laravel queues expert.
Design the event and queue architecture for a project management app:
Events and Listeners:
- TaskCreated → SendTaskCreationNotification (queued), UpdateProjectStats (queued)
- TaskAssigned → SendAssignmentEmail (queued), CreateInAppNotification (sync)
- TaskCompleted → UpdateCompletionStats, TriggerProjectCompletion (if all tasks done)
Job classes:
SendTaskCreationNotification:
- implements ShouldQueue, ShouldBeUnique (prevent duplicate emails if job retried)
- Queue: 'notifications'
- tries: 3, backoff: [60, 300, 900] (exponential)
- timeout: 30 seconds
- uniqueId(): return task ID (deduplicate per task)
- failed(): log to Slack, store in failed_notifications table
GenerateProjectReport:
- implements ShouldQueue
- Queue: 'heavy' (separate worker for CPU-intensive jobs)
- timeout: 300 seconds
- Chunk processing: process 500 tasks at a time with cursor pagination
- Progress: report progress via cache key for frontend polling
Scheduled tasks (app/Console/Kernel.php → routes/console.php in Laravel 11):
- SendOverdueTaskDigest: daily at 8am UTC per timezone
- CleanupSoftDeletedRecords: weekly (hard delete records soft-deleted 90+ days ago)
- PruneJobBatches: daily
Output: Event/Listener map, Job classes, scheduled task definitions.
5. Pest Feature Tests
You are a Pest PHP testing expert for Laravel 11.
Write Pest feature tests for the Task API endpoints:
Test setup:
- uses(RefreshDatabase::class) for DB reset per test
- Shared setup: beforeEach creates organization, admin user, member user, project
- actingAs($user, 'sanctum') for authentication
Tests (use Pest expect() API, not PHPUnit assertions):
test('member can create task in their organization project') → 201, task in DB, event dispatched
test('member cannot create task in another organization project') → 403
test('task creation requires valid due_at in future') → 422 with due_at field error
test('unauthenticated request returns 401') → 401 with www-authenticate header
test('list tasks returns only current organization tasks') → tenant isolation
test('admin can delete task, soft delete confirmed') → 204, deleted_at set in DB
test('rate limiter blocks 6th login attempt') → 429 with retry-after header
Fake facades: Event::fake(), Mail::fake(), Queue::fake()
Assert dispatched: Event::assertDispatched(TaskCreated::class, fn($e) => $e->task->id === $task->id)
Dataset example: dataset('invalid due dates', ['yesterday', 'invalid-date', '', null])
Output: full Pest test file with all test cases, beforeEach, and fake assertions.
6. Performance Optimisation
You are a Laravel performance engineer.
Audit and fix performance issues in this Laravel API controller:
[PASTE CONTROLLER CODE]
Fix:
1. N+1 queries: identify every relationship accessed in a loop, add with() or load() eager loading
2. withCount() / withSum(): replace collection->count() and collection->sum() called after loading
3. Chunking: replace Task::all()->each() with Task::chunk(500, fn) or cursor() for memory efficiency
4. Caching: identify pure reads that can use Cache::remember() with Redis (tag-based for invalidation)
5. DB indexes: list every column in where(), orderBy() calls — identify missing indexes
6. Avoid hydration: use ->select(['id','title','status']) + toArray() or pluck() instead of full model hydration for read-only endpoints
Laravel Octane consideration:
- Identify any static state or singleton state that would be unsafe under Octane (Swoole/FrankenPHP)
- Show which services need to be rebound per request
Output: fixed controller, a migration adding missing indexes, and Cache::tags() invalidation in the mutation methods.
7. Good vs Bad Laravel Prompts
| Task | ❌ Bad Prompt | ✅ Good Prompt |
|---|---|---|
| Controller | "Build a task API in Laravel" | "Build a Laravel 11 API TaskController with route model binding (tenant-scoped), CreateTaskRequest form request with authorize() + rules(), TaskResource with conditional includes, TaskPolicy for authorization, and JsonResponse 201/204 status codes. PHP 8.3." |
| Eloquent | "Query tasks from DB" | "Write an Eloquent query for tasks: eager load assignee and project (prevent N+1), apply scopeOverdue() and scopeForOrganization(), use withCount('comments'), paginate 25/page, and return TaskResource::collection(). Add the missing compound index migration." |
| Testing | "Write tests for my controller" | "Write Pest feature tests for POST /api/tasks: RefreshDatabase, actingAs with Sanctum, Event::fake() + assert TaskCreated dispatched, test tenant isolation (403 for other org), test 422 validation with dataset of invalid inputs. Use expect() API." |
Generate a custom Laravel prompt → Try PromptPrepare free
Found this helpful? Share it.