refactor: remove legacy agent and cursor configuration files and documentation
This commit is contained in:
parent
9f9ecf400e
commit
ee53672229
155 changed files with 0 additions and 21865 deletions
|
|
@ -1,483 +0,0 @@
|
|||
---
|
||||
name: ai-sdk-development
|
||||
description: TRIGGER when working with ai-sdk which is Laravel official first-party AI SDK. Activate when building, editing AI agents, chatbots, text generation, image generation, audio/TTS, transcription/STT, embeddings, RAG, vector stores, reranking, structured output, streaming, conversation memory, tools, queueing, broadcasting, and provider failover across OpenAI, Anthropic, Gemini, Azure, Groq, xAI, DeepSeek, Mistral, Ollama, ElevenLabs, Cohere, Jina, and VoyageAI. Invoke when the user references ai-sdk, the `Laravel\Ai\` namespace, or this project's AI features — not for other AI packages used directly.
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
|
||||
# Developing with the Laravel AI SDK
|
||||
|
||||
The Laravel AI SDK (`laravel/ai`) is the official AI package for Laravel, providing a unified API for agents, images, audio, transcription, embeddings, reranking, vector stores, and file management across multiple AI providers.
|
||||
|
||||
## Searching the Documentation
|
||||
|
||||
This package is new. Always search the documentation before implementing any feature. Never guess at APIs — the documentation is the single source of truth.
|
||||
|
||||
- Use broad, simple queries that match the documentation section headings below.
|
||||
- Do not add package names to queries — package information is shared automatically. Use `test agent fake`, not `laravel ai test agent fake`.
|
||||
- Run multiple queries at once — the most relevant results are returned first.
|
||||
|
||||
### Documentation Sections
|
||||
|
||||
Use these section headings as query terms for accurate results:
|
||||
|
||||
- Introduction, Installation, Configuration, Provider Support
|
||||
- Agents: Prompting, Conversation Context, Structured Output, Attachments, Streaming, Broadcasting, Queueing, Tools, Provider Tools, Middleware, Anonymous Agents, Agent Configuration
|
||||
- Images
|
||||
- Audio (TTS)
|
||||
- Transcription (STT)
|
||||
- Embeddings: Querying Embeddings, Caching Embeddings
|
||||
- Reranking
|
||||
- Files
|
||||
- Vector Stores: Adding Files to Stores
|
||||
- Failover
|
||||
- Testing: Agents, Images, Audio, Transcriptions, Embeddings, Reranking, Files, Vector Stores
|
||||
- Events
|
||||
|
||||
## Decision Workflow
|
||||
|
||||
Determine the right entry point before writing code:
|
||||
|
||||
Text generation or chat? → Agent class with `Promptable` trait
|
||||
Chat with conversation history? → Agent + `Conversational` interface (manual) or `RemembersConversations` trait (automatic)
|
||||
Structured JSON output? → Agent + `HasStructuredOutput` interface
|
||||
Image generation? → `Image::of()->generate()`
|
||||
Audio synthesis? → `Audio::of()->generate()`
|
||||
Transcription? → `Transcription::fromPath()->generate()`
|
||||
Embeddings? → `Embeddings::for()->generate()`
|
||||
Reranking? → `Reranking::of()->rerank()`
|
||||
File storage? → `Document::fromPath()->put()`
|
||||
Vector stores? → `Stores::create()`
|
||||
|
||||
## Basic Usage Examples
|
||||
|
||||
### Agents
|
||||
|
||||
```php
|
||||
use Laravel\Ai\Contracts\Agent;
|
||||
use Laravel\Ai\Enums\Lab;
|
||||
use Laravel\Ai\Promptable;
|
||||
|
||||
class SalesCoach implements Agent
|
||||
{
|
||||
use Promptable;
|
||||
|
||||
public function instructions(): string
|
||||
{
|
||||
return 'You are a sales coach.';
|
||||
}
|
||||
}
|
||||
|
||||
// Prompting
|
||||
$response = (new SalesCoach)->prompt('Analyze this transcript...');
|
||||
echo $response->text;
|
||||
|
||||
// Container resolution with dependency injection
|
||||
$agent = SalesCoach::make(user: $user);
|
||||
|
||||
// Override provider, model, or timeout per-prompt
|
||||
$response = (new SalesCoach)->prompt(
|
||||
'Analyze this transcript...',
|
||||
provider: Lab::Anthropic,
|
||||
model: 'claude-haiku-4-5-20251001',
|
||||
timeout: 120,
|
||||
);
|
||||
|
||||
// Streaming (returns SSE response from a route)
|
||||
return (new SalesCoach)->stream('Analyze this transcript...');
|
||||
|
||||
// Queueing
|
||||
(new SalesCoach)->queue('Analyze this transcript...')
|
||||
->then(fn ($response) => /* ... */);
|
||||
|
||||
// Anonymous agents
|
||||
use function Laravel\Ai\{agent};
|
||||
|
||||
$response = agent(instructions: 'You are a helpful assistant.')->prompt('Hello');
|
||||
```
|
||||
|
||||
### Conversation Context
|
||||
|
||||
Manual conversation history via the `Conversational` interface:
|
||||
|
||||
```php
|
||||
use Laravel\Ai\Contracts\Agent;
|
||||
use Laravel\Ai\Contracts\Conversational;
|
||||
use Laravel\Ai\Messages\Message;
|
||||
use Laravel\Ai\Promptable;
|
||||
|
||||
class SalesCoach implements Agent, Conversational
|
||||
{
|
||||
use Promptable;
|
||||
|
||||
public function __construct(public User $user) {}
|
||||
|
||||
public function instructions(): string { return 'You are a sales coach.'; }
|
||||
|
||||
public function messages(): iterable
|
||||
{
|
||||
return History::where('user_id', $this->user->id)
|
||||
->latest()->limit(50)->get()->reverse()
|
||||
->map(fn ($m) => new Message($m->role, $m->content))
|
||||
->all();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Automatic conversation persistence via the `RemembersConversations` trait:
|
||||
|
||||
```php
|
||||
use Laravel\Ai\Concerns\RemembersConversations;
|
||||
use Laravel\Ai\Contracts\Agent;
|
||||
use Laravel\Ai\Contracts\Conversational;
|
||||
use Laravel\Ai\Promptable;
|
||||
|
||||
class SalesCoach implements Agent, Conversational
|
||||
{
|
||||
use Promptable, RemembersConversations;
|
||||
|
||||
public function instructions(): string { return 'You are a sales coach.'; }
|
||||
}
|
||||
|
||||
// Start a new conversation
|
||||
$response = (new SalesCoach)->forUser($user)->prompt('Hello!');
|
||||
$conversationId = $response->conversationId;
|
||||
|
||||
// Continue an existing conversation
|
||||
$response = (new SalesCoach)->continue($conversationId, as: $user)->prompt('Tell me more.');
|
||||
```
|
||||
|
||||
### Structured Output
|
||||
|
||||
```php
|
||||
use Illuminate\Contracts\JsonSchema\JsonSchema;
|
||||
use Laravel\Ai\Contracts\Agent;
|
||||
use Laravel\Ai\Contracts\HasStructuredOutput;
|
||||
use Laravel\Ai\Promptable;
|
||||
|
||||
class Reviewer implements Agent, HasStructuredOutput
|
||||
{
|
||||
use Promptable;
|
||||
|
||||
public function instructions(): string { return 'Review and score content.'; }
|
||||
|
||||
public function schema(JsonSchema $schema): array
|
||||
{
|
||||
return [
|
||||
'feedback' => $schema->string()->required(),
|
||||
'score' => $schema->integer()->min(1)->max(10)->required(),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
$response = (new Reviewer)->prompt('Review this...');
|
||||
echo $response['score']; // Access like an array
|
||||
```
|
||||
|
||||
### Images
|
||||
|
||||
```php
|
||||
use Laravel\Ai\Image;
|
||||
|
||||
$image = Image::of('A sunset over mountains')
|
||||
->landscape()
|
||||
->quality('high')
|
||||
->generate();
|
||||
|
||||
$path = $image->store(); // Store to default disk
|
||||
```
|
||||
|
||||
### Audio
|
||||
|
||||
```php
|
||||
use Laravel\Ai\Audio;
|
||||
|
||||
$audio = Audio::of('Hello from Laravel.')
|
||||
->female()
|
||||
->instructions('Speak warmly')
|
||||
->generate();
|
||||
|
||||
$path = $audio->store();
|
||||
```
|
||||
|
||||
### Transcription
|
||||
|
||||
```php
|
||||
use Laravel\Ai\Transcription;
|
||||
|
||||
$transcript = Transcription::fromStorage('audio.mp3')
|
||||
->diarize()
|
||||
->generate();
|
||||
|
||||
echo (string) $transcript;
|
||||
```
|
||||
|
||||
### Embeddings
|
||||
|
||||
```php
|
||||
use Laravel\Ai\Embeddings;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
$response = Embeddings::for(['Text one', 'Text two'])
|
||||
->dimensions(1536)
|
||||
->cache()
|
||||
->generate();
|
||||
|
||||
// Single string via Stringable
|
||||
$embedding = Str::of('Napa Valley has great wine.')->toEmbeddings();
|
||||
```
|
||||
|
||||
### Reranking
|
||||
|
||||
```php
|
||||
use Laravel\Ai\Reranking;
|
||||
|
||||
$response = Reranking::of(['Django is Python.', 'Laravel is PHP.', 'React is JS.'])
|
||||
->limit(5)
|
||||
->rerank('PHP frameworks');
|
||||
|
||||
$response->first()->document; // "Laravel is PHP."
|
||||
```
|
||||
|
||||
### Files and Vector Stores
|
||||
|
||||
```php
|
||||
use Laravel\Ai\Files\Document;
|
||||
use Laravel\Ai\Stores;
|
||||
|
||||
// Store a file with the provider
|
||||
$file = Document::fromPath('/path/to/doc.pdf')->put();
|
||||
|
||||
// Create a vector store and add files
|
||||
$store = Stores::create('Knowledge Base');
|
||||
$store->add($file->id);
|
||||
$store->add(Document::fromStorage('manual.pdf')); // Store + add in one step
|
||||
```
|
||||
|
||||
## Agent Configuration
|
||||
|
||||
### PHP Attributes
|
||||
|
||||
```php
|
||||
use Laravel\Ai\Attributes\{Provider, Model, MaxSteps, MaxTokens, Temperature, Timeout};
|
||||
use Laravel\Ai\Enums\Lab;
|
||||
|
||||
#[Provider(Lab::Anthropic)]
|
||||
#[Model('claude-haiku-4-5-20251001')]
|
||||
#[MaxSteps(10)]
|
||||
#[MaxTokens(4096)]
|
||||
#[Temperature(0.7)]
|
||||
#[Timeout(120)]
|
||||
class MyAgent implements Agent
|
||||
{
|
||||
use Promptable;
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
The `#[UseCheapestModel]` and `#[UseSmartestModel]` attributes are also available for automatic model selection.
|
||||
|
||||
The `#[WithoutBroadcasting]` attribute stops the given stream event types from broadcasting (e.g. data-heavy `ToolResult` payloads that exceed the WebSocket frame limit). The events are still streamed and persisted; they just never hit the channel:
|
||||
|
||||
```php
|
||||
use Laravel\Ai\Attributes\WithoutBroadcasting;
|
||||
use Laravel\Ai\Streaming\Events\{ToolCall, ToolResult};
|
||||
|
||||
#[WithoutBroadcasting(ToolResult::class, ToolCall::class)]
|
||||
class SearchAgent implements Agent, HasTools
|
||||
{
|
||||
use Promptable;
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
### Tools
|
||||
|
||||
Implement the `HasTools` interface and scaffold tools with `php artisan make:tool`:
|
||||
|
||||
```php
|
||||
use Laravel\Ai\Contracts\HasTools;
|
||||
|
||||
class MyAgent implements Agent, HasTools
|
||||
{
|
||||
use Promptable;
|
||||
|
||||
public function tools(): iterable
|
||||
{
|
||||
return [new MyCustomTool];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Provider Tools
|
||||
|
||||
```php
|
||||
use Laravel\Ai\Providers\Tools\{WebSearch, WebFetch, FileSearch};
|
||||
|
||||
public function tools(): iterable
|
||||
{
|
||||
return [
|
||||
(new WebSearch)->max(5)->allow(['laravel.com']),
|
||||
new WebFetch,
|
||||
new FileSearch(stores: ['store_id']),
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
### Conversation Memory
|
||||
|
||||
```php
|
||||
use Laravel\Ai\Concerns\RemembersConversations;
|
||||
use Laravel\Ai\Contracts\Conversational;
|
||||
|
||||
class ChatBot implements Agent, Conversational
|
||||
{
|
||||
use Promptable, RemembersConversations;
|
||||
// ...
|
||||
}
|
||||
|
||||
$response = (new ChatBot)->forUser($user)->prompt('Hello!');
|
||||
$response = (new ChatBot)->continue($conversationId, as: $user)->prompt('More...');
|
||||
```
|
||||
|
||||
### Failover
|
||||
|
||||
```php
|
||||
$response = (new MyAgent)->prompt('Hello', provider: [Lab::OpenAI, Lab::Anthropic]);
|
||||
```
|
||||
|
||||
## Testing and Faking
|
||||
|
||||
Each capability supports `fake()` with assertions:
|
||||
|
||||
```php
|
||||
use App\Ai\Agents\SalesCoach;
|
||||
use Laravel\Ai\{Image, Audio, Transcription, Embeddings, Reranking, Files, Stores};
|
||||
|
||||
// Agents
|
||||
SalesCoach::fake(['Response 1', 'Response 2']);
|
||||
SalesCoach::assertPrompted('query');
|
||||
SalesCoach::assertNotPrompted('query');
|
||||
SalesCoach::assertNeverPrompted();
|
||||
SalesCoach::fake()->preventStrayPrompts();
|
||||
|
||||
// Images
|
||||
Image::fake();
|
||||
Image::assertGenerated(fn ($prompt) => $prompt->contains('sunset'));
|
||||
Image::assertNothingGenerated();
|
||||
|
||||
// Audio
|
||||
Audio::fake();
|
||||
Audio::assertGenerated(fn ($prompt) => $prompt->contains('Hello'));
|
||||
|
||||
// Transcription
|
||||
Transcription::fake(['Transcribed text.']);
|
||||
Transcription::assertGenerated(fn ($prompt) => $prompt->isDiarized());
|
||||
|
||||
// Embeddings
|
||||
Embeddings::fake();
|
||||
Embeddings::assertGenerated(fn ($prompt) => $prompt->contains('Laravel'));
|
||||
|
||||
// Reranking
|
||||
Reranking::fake();
|
||||
Reranking::assertReranked(fn ($prompt) => $prompt->contains('PHP'));
|
||||
|
||||
// Files
|
||||
Files::fake();
|
||||
Files::assertStored(fn ($file) => $file->mimeType() === 'text/plain');
|
||||
|
||||
// Stores
|
||||
Stores::fake();
|
||||
Stores::assertCreated('Knowledge Base');
|
||||
$store = Stores::get('id');
|
||||
$store->assertAdded('file_id');
|
||||
```
|
||||
|
||||
## Key Patterns
|
||||
|
||||
- Namespace: `Laravel\Ai\`
|
||||
- Package: `composer require laravel/ai`
|
||||
- Agent pattern: Implement the `Agent` interface and use the `Promptable` trait
|
||||
- Optional interfaces: `HasTools`, `HasMiddleware`, `HasStructuredOutput`, `Conversational`
|
||||
- Entry-point classes: `Image`, `Audio`, `Transcription`, `Embeddings`, `Reranking`, `Stores`
|
||||
- Provider enum: `Laravel\Ai\Enums\Lab` (prefer over plain strings)
|
||||
- Artisan commands: `php artisan make:agent`, `php artisan make:tool`
|
||||
- Global helper: `agent()` for anonymous agents
|
||||
|
||||
## OpenAI-Compatible Provider
|
||||
|
||||
Point the SDK at any OpenAI-compatible endpoint (LM Studio, vLLM, Together, etc.) with the config-driven `openai-compatible` driver. Define named instances in `config/ai.php`, no code required:
|
||||
|
||||
```php
|
||||
'my-llm' => [
|
||||
'driver' => 'openai-compatible',
|
||||
'url' => env('MY_LLM_URL'), // required
|
||||
'key' => env('MY_LLM_API_KEY'), // optional Bearer token
|
||||
'models' => [
|
||||
'text' => ['default' => 'some-chat-model'],
|
||||
'embeddings' => [
|
||||
'default' => 'some-embedding-model',
|
||||
'dimensions' => 1024, // optional; omit to use native dimensions
|
||||
],
|
||||
],
|
||||
],
|
||||
```
|
||||
|
||||
Reference it by config key (or `Lab::OpenAiCompatible`). A model is required via the corresponding `models` configuration or per-call `model:`:
|
||||
|
||||
```php
|
||||
agent()->prompt('Hello', provider: 'my-llm', model: 'some-model');
|
||||
|
||||
Embeddings::for(['Hello'])->generate(
|
||||
provider: 'my-llm',
|
||||
model: 'some-embedding-model',
|
||||
);
|
||||
```
|
||||
|
||||
It uses OpenAI-standard shapes and supports text, streaming, tools, structured output, image attachments, and text embeddings. Embedding dimensions are optional; omit them to use the model's native dimensions. For extra request-body fields, implement `HasProviderOptions` — the returned array is merged into the body.
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
### Wrong Namespace
|
||||
|
||||
The namespace is `Laravel\Ai`, not `Illuminate\Ai` or `Laravel\AI`.
|
||||
|
||||
```php
|
||||
// Correct
|
||||
use Laravel\Ai\Image;
|
||||
use Laravel\Ai\Contracts\Agent;
|
||||
use Laravel\Ai\Promptable;
|
||||
|
||||
// Wrong — these do not exist
|
||||
use Illuminate\Ai\Image;
|
||||
use Laravel\AI\Agent;
|
||||
```
|
||||
|
||||
### Unsupported Provider Capability
|
||||
|
||||
Calling a capability not supported by a provider throws a `LogicException`. Refer to the provider support table below.
|
||||
|
||||
## Provider Support
|
||||
|
||||
| Feature | Providers |
|
||||
| ---------- | --------------------------------------------------------------- |
|
||||
| Text | OpenAI, Anthropic, Gemini, Azure, Groq, xAI, DeepSeek, Mistral, Ollama, OpenRouter, OpenAI-compatible |
|
||||
| Images | OpenAI, Gemini, xAI |
|
||||
| TTS | OpenAI, ElevenLabs |
|
||||
| STT | OpenAI, ElevenLabs, Mistral |
|
||||
| Embeddings | OpenAI, OpenAI-compatible, Gemini, Azure, Cohere, Mistral, Jina, VoyageAI |
|
||||
| Reranking | Cohere, Jina |
|
||||
| Files | OpenAI, Anthropic, Gemini |
|
||||
|
||||
Use the `Laravel\Ai\Enums\Lab` enum to reference providers in code instead of plain strings:
|
||||
|
||||
```php
|
||||
use Laravel\Ai\Enums\Lab;
|
||||
|
||||
Lab::Anthropic;
|
||||
Lab::OpenAI;
|
||||
Lab::Gemini;
|
||||
Lab::OpenAiCompatible; // configurable OpenAI-compatible endpoint
|
||||
// ...
|
||||
```
|
||||
|
|
@ -1,98 +0,0 @@
|
|||
---
|
||||
name: cashier-stripe-development
|
||||
description: "Handles Laravel Cashier Stripe integration including subscriptions, webhooks, Stripe Checkout, invoices, charges, refunds, trials, coupons, metered billing, and payment failure handling. Triggered when a user mentions Cashier, Billable, IncompletePayment, stripe_id, newSubscription, Stripe subscriptions, or billing. Also applies when setting up webhooks, handling SCA/3DS payment failures, testing with Stripe test cards, or troubleshooting incomplete subscriptions, CSRF webhook errors, or migration publish issues."
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
|
||||
# Cashier Stripe Development
|
||||
|
||||
## Documentation
|
||||
|
||||
Use `search-docs` for detailed Cashier patterns and documentation covering subscriptions, webhooks, Stripe Checkout, invoices, payment methods, and testing.
|
||||
|
||||
For deeper guidance on specific topics, read the relevant reference file before implementing:
|
||||
|
||||
- `references/subscriptions.md` covers subscription creation, status checks, swapping, trials, quantities, and multiple products
|
||||
- `references/webhooks.md` covers webhook setup, custom handlers, CSRF exclusion, and local development with the Stripe CLI
|
||||
- `references/testing.md` covers Stripe test cards, payment method tokens, and feature test patterns
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
php artisan vendor:publish --tag="cashier-migrations"
|
||||
php artisan migrate
|
||||
php artisan vendor:publish --tag="cashier-config"
|
||||
```
|
||||
|
||||
### Environment Variables
|
||||
|
||||
```
|
||||
STRIPE_KEY=pk_test_...
|
||||
STRIPE_SECRET=sk_test_...
|
||||
STRIPE_WEBHOOK_SECRET=whsec_...
|
||||
CASHIER_CURRENCY=usd
|
||||
CASHIER_CURRENCY_LOCALE=en_US
|
||||
```
|
||||
|
||||
### Billable Model
|
||||
|
||||
<!-- Add Billable Trait -->
|
||||
```php
|
||||
use Laravel\Cashier\Billable;
|
||||
|
||||
class User extends Authenticatable
|
||||
{
|
||||
use Billable;
|
||||
}
|
||||
```
|
||||
|
||||
For a non-User model, register it in a service provider:
|
||||
|
||||
<!-- Custom Billable Model -->
|
||||
```php
|
||||
// In AppServiceProvider::boot()
|
||||
Cashier::useCustomerModel(Team::class);
|
||||
```
|
||||
|
||||
### Creating a Subscription
|
||||
|
||||
<!-- Create Subscription -->
|
||||
```php
|
||||
use Laravel\Cashier\Exceptions\IncompletePayment;
|
||||
|
||||
try {
|
||||
$user->newSubscription('default', 'price_xxxx')->create($paymentMethodId);
|
||||
} catch (IncompletePayment $e) {
|
||||
return redirect()->route('cashier.payment', [$e->payment->id, 'redirect' => route('home')]);
|
||||
}
|
||||
```
|
||||
|
||||
Always wrap subscription creation in a try/catch for `IncompletePayment`. When a card requires 3DS authentication, Cashier throws this exception. The `cashier.payment` route is auto-registered and handles the confirmation flow.
|
||||
|
||||
## Verification
|
||||
|
||||
1. Run migrations and confirm `stripe_id`, `pm_type`, `pm_last_four`, and `trial_ends_at` columns exist on the billable model table
|
||||
2. Test the webhook endpoint with `stripe listen --forward-to localhost/stripe/webhook` if you use the default path, or swap `stripe` for your configured `CASHIER_PATH`
|
||||
3. Confirm `$user->subscribed('default')` returns the expected value for active and incomplete subscriptions
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
- The migration publish tag is `cashier-migrations`, not `cashier`. Running `migrate` before publishing results in missing columns and tables.
|
||||
- `CASHIER_CURRENCY` must be set explicitly. It defaults to USD, which silently breaks non-US apps.
|
||||
- The Stripe CLI generates its own webhook signing secret. It is different from the Dashboard endpoint secret. Using the wrong one causes signature verification failures.
|
||||
- The webhook route must be excluded from CSRF verification using your configured `cashier.path`. If you change `CASHIER_PATH` from `stripe` to `billing`, exclude `billing/*`, not `stripe/*`.
|
||||
- `canceled()` returns true as soon as `cancel()` is called, but the user still has access during the grace period. Use `ended()` to confirm access is fully revoked.
|
||||
- `subscribed()` returns true during the grace period even though the subscription is canceled.
|
||||
- `subscribed()` returns false for `incomplete` and `past_due` subscriptions by default.
|
||||
- Prices cannot be swapped and quantity cannot be updated while a subscription has an incomplete payment.
|
||||
- When extending `WebhookController`, call `Cashier::ignoreRoutes()` in a service provider and re-register both `cashier.payment` and `cashier.webhook` under the configured `cashier.path`.
|
||||
- Use `Cashier::useCustomerModel()` in a service provider to set a custom billable model. There is no `CASHIER_MODEL` env var.
|
||||
- `trial_ends_at` is a local database column synced via webhooks. It will be stale if webhooks are not configured in production.
|
||||
- In MySQL, the `stripe_id` column must use `utf8_bin` collation to avoid case-sensitivity issues.
|
||||
- `noProrate()` has no effect when combined with `swapAndInvoice()`. That method always prorates.
|
||||
- Methods like `withPromotionCode()` require the Stripe API ID such as `promo_xxxx`, not the customer-facing code. Use `findPromotionCode()` to resolve a code to its ID.
|
||||
- Always use `search-docs` for the latest Cashier documentation rather than relying on this skill alone.
|
||||
|
|
@ -1,108 +0,0 @@
|
|||
# Subscriptions Reference
|
||||
|
||||
Use `search-docs` for authoritative documentation on subscriptions.
|
||||
|
||||
## Status Checks
|
||||
|
||||
| Method | Returns true when |
|
||||
|---|---|
|
||||
| `$user->subscribed('default')` | Active or on grace period |
|
||||
| `->onTrial()` | Trial period active |
|
||||
| `->onGracePeriod()` | Canceled, period not yet ended |
|
||||
| `->canceled()` | `ends_at` is set, may still have access |
|
||||
| `->ended()` | Canceled and grace period expired |
|
||||
| `->incomplete()` | Awaiting SCA/3DS confirmation |
|
||||
| `->pastDue()` | Payment overdue |
|
||||
| `->recurring()` | Active and not on trial |
|
||||
|
||||
Check by product or price:
|
||||
|
||||
```php
|
||||
$user->subscribedToProduct('prod_premium', 'default');
|
||||
$user->subscribedToPrice('price_monthly', 'default');
|
||||
```
|
||||
|
||||
## Swapping Plans
|
||||
|
||||
```php
|
||||
$user->subscription('default')->swap('price_new');
|
||||
$user->subscription('default')->noProrate()->swap('price_new');
|
||||
$user->subscription('default')->swapAndInvoice('price_new');
|
||||
$user->subscription('default')->skipTrial()->swap('price_new');
|
||||
```
|
||||
|
||||
## Quantity
|
||||
|
||||
```php
|
||||
$user->subscription('default')->incrementQuantity();
|
||||
$user->subscription('default')->decrementQuantity();
|
||||
$user->subscription('default')->updateQuantity(10);
|
||||
$user->subscription('default')->noProrate()->updateQuantity(10);
|
||||
```
|
||||
|
||||
## Trials
|
||||
|
||||
```php
|
||||
$user->newSubscription('default', 'price_xxxx')
|
||||
->trialDays(14)
|
||||
->create($paymentMethodId);
|
||||
|
||||
$subscription->extendTrial(now()->addDays(7));
|
||||
```
|
||||
|
||||
## Multiple Products on One Subscription
|
||||
|
||||
```php
|
||||
$user->newSubscription('default', ['price_monthly', 'price_chat'])
|
||||
->quantity(5, 'price_chat')
|
||||
->create($paymentMethod);
|
||||
|
||||
$user->subscription('default')->addPrice('price_chat');
|
||||
$user->subscription('default')->removePrice('price_chat');
|
||||
$user->subscription('default')->swap(['price_pro', 'price_chat']);
|
||||
```
|
||||
|
||||
## Multiple Subscriptions
|
||||
|
||||
```php
|
||||
$user->newSubscription('swimming', 'price_swimming_monthly')->create($pm);
|
||||
$user->newSubscription('gym', 'price_gym_monthly')->create($pm);
|
||||
|
||||
$user->subscription('swimming')->swap('price_swimming_yearly');
|
||||
$user->subscription('gym')->cancel();
|
||||
```
|
||||
|
||||
## Cancellation and Resumption
|
||||
|
||||
```php
|
||||
$user->subscription('default')->cancel(); // At end of billing period
|
||||
$user->subscription('default')->cancelNow(); // Immediately
|
||||
$user->subscription('default')->resume(); // During grace period only
|
||||
```
|
||||
|
||||
## Incomplete Payment Handling
|
||||
|
||||
```php
|
||||
if ($user->hasIncompletePayment('default')) {
|
||||
$paymentId = $user->subscription('default')->latestPayment()->id;
|
||||
return redirect()->route('cashier.payment', $paymentId);
|
||||
}
|
||||
```
|
||||
|
||||
Opt out of default deactivation behavior:
|
||||
|
||||
```php
|
||||
Cashier::keepPastDueSubscriptionsActive();
|
||||
Cashier::keepIncompleteSubscriptionsActive();
|
||||
```
|
||||
|
||||
## Metered / Usage-Based Billing
|
||||
|
||||
```php
|
||||
$user->newSubscription('default')
|
||||
->meteredPrice('price_metered')
|
||||
->create($paymentMethodId);
|
||||
|
||||
$user->reportMeterEvent('emails-sent');
|
||||
$user->reportMeterEvent('emails-sent', quantity: 15);
|
||||
```
|
||||
|
|
@ -1,52 +0,0 @@
|
|||
# Testing Reference
|
||||
|
||||
Use `search-docs` for authoritative documentation on testing Cashier integrations.
|
||||
|
||||
## Test Cards and Tokens
|
||||
|
||||
Use card numbers for browser-based flows (Stripe.js / Checkout). Use `pm_card_*` tokens directly in feature tests that call the Stripe API.
|
||||
|
||||
| Card Number | Token | Behavior |
|
||||
|---|---|---|
|
||||
| `4242 4242 4242 4242` | `pm_card_visa` | Succeeds immediately |
|
||||
| `4000 0025 0000 3155` | `pm_card_threeDSecure2Required` | Requires SCA/3DS |
|
||||
| `4000 0027 6000 3184` | `pm_card_authenticationRequired` | Requires authentication |
|
||||
| `4000 0000 0000 9995` | `pm_card_chargeDeclinedInsufficientFunds` | Declined, insufficient funds |
|
||||
| `4000 0000 0000 0002` | `pm_card_chargeDeclined` | Declined |
|
||||
|
||||
Use expiry `12/34`, any CVC, any ZIP for card number inputs.
|
||||
|
||||
## Feature Test Example
|
||||
|
||||
Feature tests that hit the real Stripe test API use `pm_card_*` tokens:
|
||||
|
||||
```php
|
||||
public function test_user_can_subscribe(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$user->newSubscription('default', 'price_xxxx')
|
||||
->create('pm_card_visa');
|
||||
|
||||
$this->assertTrue($user->subscribed('default'));
|
||||
}
|
||||
|
||||
public function test_incomplete_payment_is_handled(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
try {
|
||||
$user->newSubscription('default', 'price_xxxx')
|
||||
->create('pm_card_threeDSecure2Required');
|
||||
} catch (\Laravel\Cashier\Exceptions\IncompletePayment $e) {
|
||||
$this->assertTrue($user->subscription('default')->incomplete());
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Setup Notes
|
||||
|
||||
- Use Stripe test mode keys (`sk_test_...`, `pk_test_...`) in your test environment
|
||||
- Cashier does not ship a global `fake()` helper. Tests hit the real Stripe test API by default.
|
||||
- Refer to `tests/Feature/` in the Cashier package itself for integration test patterns covering subscription creation, payment methods, and webhook handling
|
||||
- Use `search-docs` for current guidance on mocking Stripe HTTP calls or using Stripe's test clock feature for time-sensitive scenarios
|
||||
|
|
@ -1,132 +0,0 @@
|
|||
# Webhooks Reference
|
||||
|
||||
Use `search-docs` for authoritative documentation on webhooks.
|
||||
|
||||
## Auto-Registered Routes
|
||||
|
||||
Cashier registers two routes automatically under the `cashier.path` prefix (`config('cashier.path')`, default `stripe`):
|
||||
|
||||
- `POST /{cashier.path}/webhook` named `cashier.webhook`
|
||||
- `GET /{cashier.path}/payment/{id}` named `cashier.payment`
|
||||
|
||||
With the default config these are `/stripe/webhook` and `/stripe/payment/{id}`. If you set `CASHIER_PATH=billing`, they become `/billing/webhook` and `/billing/payment/{id}`.
|
||||
|
||||
## CSRF Exclusion
|
||||
|
||||
Use the same path prefix you configured for Cashier here. If `CASHIER_PATH=billing`, exclude `billing/*` instead of `stripe/*`.
|
||||
|
||||
**Laravel 11+ (`bootstrap/app.php`, default path example):**
|
||||
|
||||
```php
|
||||
->withMiddleware(function (Middleware $middleware) {
|
||||
$middleware->validateCsrfTokens(except: ['stripe/*']);
|
||||
})
|
||||
```
|
||||
|
||||
**Laravel 10 (`app/Http/Middleware/VerifyCsrfToken.php`, default path example):**
|
||||
|
||||
```php
|
||||
protected $except = [
|
||||
'stripe/*',
|
||||
];
|
||||
```
|
||||
|
||||
## Local Development with Stripe CLI
|
||||
|
||||
If you changed `cashier.path`, forward Stripe CLI events to that URL instead of `/stripe/webhook`.
|
||||
|
||||
```bash
|
||||
stripe login
|
||||
stripe listen --forward-to your-app.test/stripe/webhook
|
||||
stripe trigger invoice.payment_succeeded
|
||||
```
|
||||
|
||||
The CLI outputs a `whsec_...` signing secret specific to that session. Set it as `STRIPE_WEBHOOK_SECRET` locally. It is not the same as the Dashboard endpoint secret.
|
||||
|
||||
## Registering Events in the Stripe Dashboard
|
||||
|
||||
Use the Artisan command to create the endpoint automatically with all required events:
|
||||
|
||||
```bash
|
||||
php artisan cashier:webhook
|
||||
```
|
||||
|
||||
Cashier's `cashier:webhook` command registers these events by default:
|
||||
|
||||
- `customer.subscription.created`
|
||||
- `customer.subscription.updated`
|
||||
- `customer.subscription.deleted`
|
||||
- `customer.updated` / `customer.deleted`
|
||||
- `invoice.payment_action_required`
|
||||
- `invoice.payment_succeeded`
|
||||
- `payment_method.automatically_updated`
|
||||
|
||||
Cashier's `WebhookController` has built-in handlers for all of the above except `invoice.payment_succeeded`. For renewal hooks, prefer `WebhookReceived` / `WebhookHandled` listeners unless you intentionally add your own controller method.
|
||||
|
||||
## Custom Handlers: Extending WebhookController
|
||||
|
||||
Method name pattern: `handle` + StudlyCase of event type with dots replaced by underscores.
|
||||
|
||||
`customer.subscription.created` becomes `handleCustomerSubscriptionCreated`.
|
||||
|
||||
```php
|
||||
use Laravel\Cashier\Http\Controllers\WebhookController as CashierController;
|
||||
|
||||
class StripeWebhookController extends CashierController
|
||||
{
|
||||
public function handleCustomerSubscriptionCreated(array $payload)
|
||||
{
|
||||
$response = parent::handleCustomerSubscriptionCreated($payload);
|
||||
|
||||
// your logic after Cashier syncs the subscription
|
||||
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If you add a method for an event Cashier does not handle internally, such as `invoice.payment_succeeded`, do not call `parent::handle...()` unless the base controller actually defines that method.
|
||||
|
||||
In a service provider, disable auto-registration and re-register both Cashier routes so the incomplete-payment flow and `cashier:webhook` command keep working:
|
||||
|
||||
```php
|
||||
Cashier::ignoreRoutes();
|
||||
```
|
||||
|
||||
```php
|
||||
// routes/web.php
|
||||
use App\Http\Controllers\StripeWebhookController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Laravel\Cashier\Http\Controllers\PaymentController;
|
||||
|
||||
Route::prefix(config('cashier.path'))
|
||||
->name('cashier.')
|
||||
->group(function () {
|
||||
Route::get('payment/{id}', [PaymentController::class, 'show'])->name('payment');
|
||||
Route::post('webhook', [StripeWebhookController::class, 'handleWebhook'])->name('webhook');
|
||||
});
|
||||
```
|
||||
|
||||
Keep the `cashier.webhook` route name unless you plan to pass `--url` explicitly to `php artisan cashier:webhook`.
|
||||
|
||||
## Custom Handlers: Listening to Events
|
||||
|
||||
The simpler option when you do not need to replace Cashier's internal logic, or when you want to react to events such as `invoice.payment_succeeded` that Cashier does not process itself:
|
||||
|
||||
```php
|
||||
use Laravel\Cashier\Events\WebhookReceived;
|
||||
use Laravel\Cashier\Events\WebhookHandled;
|
||||
|
||||
// WebhookReceived fires for every event before Cashier processes it
|
||||
// WebhookHandled fires after Cashier processes it
|
||||
|
||||
Event::listen(WebhookReceived::class, function (WebhookReceived $event) {
|
||||
if ($event->payload['type'] === 'invoice.payment_succeeded') {
|
||||
// handle renewal
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## Signature Verification
|
||||
|
||||
`VerifyWebhookSignature` middleware is applied automatically when `cashier.webhook.secret` is set. No extra wiring is needed.
|
||||
|
|
@ -1,404 +0,0 @@
|
|||
---
|
||||
name: configure-nightwatch
|
||||
description: Configures Laravel Nightwatch data collection, sampling rates, filtering rules, and redaction policies. Use when setting up Nightwatch, managing data volume, protecting sensitive data (PII), or optimizing event collection for production workloads.
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
|
||||
# Nightwatch Configuration Guide
|
||||
|
||||
This skill helps configure Laravel Nightwatch data collection to balance observability, performance, and privacy. Covers sampling strategies, filtering rules, and redaction methods across all event types.
|
||||
|
||||
## Documentation Reference
|
||||
|
||||
The [Nightwatch Documentation](https://nightwatch.laravel.com/docs) is the definitive and up-to-date source of information for all Nightwatch configuration options. This skill provides practical guidance and common patterns, but always consult the official documentation as the primary source of truth for specific details, environment variables, and API behavior. The documentation includes comprehensive coverage of:
|
||||
|
||||
- [Filtering and Configuration](https://nightwatch.laravel.com/docs/filtering) - Core concepts for sampling, filtering, and redaction
|
||||
- Individual event type pages with specific configuration options:
|
||||
- [Requests](https://nightwatch.laravel.com/docs/requests) - Request sampling, header handling, payload capture
|
||||
- [Commands](https://nightwatch.laravel.com/docs/commands) - Command sampling and redaction
|
||||
- [Queries](https://nightwatch.laravel.com/docs/queries) - Query filtering and redaction
|
||||
- [Cache](https://nightwatch.laravel.com/docs/cache) - Cache event filtering by key or pattern
|
||||
- [Jobs](https://nightwatch.laravel.com/docs/jobs) - Job filtering and sampling decoupling
|
||||
- [Mail](https://nightwatch.laravel.com/docs/mail) - Mail event filtering
|
||||
- [Notifications](https://nightwatch.laravel.com/docs/notifications) - Notification filtering by channel
|
||||
- [Exceptions](https://nightwatch.laravel.com/docs/exceptions) - Exception sampling and throttling
|
||||
- [Outgoing Requests](https://nightwatch.laravel.com/docs/outgoing-requests) - HTTP request filtering
|
||||
- [reference.md](reference.md) - Quick lookup table by event type, production presets, and verification checklist
|
||||
|
||||
## Data Collection Flow
|
||||
|
||||
Nightwatch processes events through three stages:
|
||||
|
||||
1. **Sampling** - Controls which entry points are captured (requests, commands, scheduled tasks)
|
||||
2. **Filtering** - Excludes specific events after sampling (queries, cache, mail, etc.)
|
||||
3. **Redaction** - Modifies captured data to remove/obfuscate sensitive information
|
||||
|
||||
```
|
||||
Request/Command/Scheduled Task
|
||||
|
|
||||
v
|
||||
[Sampling?] ----NO----> Drop entire trace
|
||||
| YES
|
||||
v
|
||||
Events generated
|
||||
|
|
||||
v
|
||||
[Filtering?] ----YES---> Drop specific event
|
||||
| NO
|
||||
v
|
||||
[Redaction] ----------> Store modified data
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Sampling Configuration
|
||||
|
||||
Sampling determines which entry points (requests, commands, scheduled tasks) trigger full trace collection. When an entry point is sampled, all related events are captured.
|
||||
|
||||
### Global Sample Rates
|
||||
|
||||
Configure via environment variables:
|
||||
|
||||
```bash
|
||||
|
||||
# Default: 100% sampling (all requests/commands captured)
|
||||
|
||||
NIGHTWATCH_REQUEST_SAMPLE_RATE=0.1 # Recommended: 10% of requests
|
||||
|
||||
NIGHTWATCH_COMMAND_SAMPLE_RATE=1.0 # Capture all commands
|
||||
|
||||
NIGHTWATCH_EXCEPTION_SAMPLE_RATE=1.0 # Always capture exceptions
|
||||
|
||||
```
|
||||
|
||||
**Recommendation**: Start with `0.1` (10%) for requests in production, adjust based on volume and needs.
|
||||
|
||||
### Route-Based Sampling
|
||||
|
||||
Apply different rates to specific routes using the `Sample` middleware:
|
||||
|
||||
```php routes/web.php
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Laravel\Nightwatch\Http\Middleware\Sample;
|
||||
|
||||
// Sample admin routes at 100%
|
||||
Route::middleware(Sample::rate(1.0))->prefix('admin')->group(function () {
|
||||
// All admin routes sampled fully
|
||||
});
|
||||
|
||||
// Sample API routes at 5%
|
||||
Route::middleware(Sample::rate(0.05))->prefix('api')->group(function () {
|
||||
// API routes sampled sparingly
|
||||
});
|
||||
|
||||
// Always sample critical endpoints
|
||||
Route::post('/checkout', [CheckoutController::class, 'process'])
|
||||
->middleware(Sample::always());
|
||||
|
||||
// Never sample health checks
|
||||
Route::get('/health', [HealthController::class, 'check'])
|
||||
->middleware(Sample::never());
|
||||
```
|
||||
|
||||
### Unmatched Route Sampling
|
||||
|
||||
Handle 404/bot traffic with reduced sampling:
|
||||
|
||||
```php routes/web.php
|
||||
Route::fallback(fn () => abort(404))
|
||||
->middleware(Sample::rate(0.01)); // 1% sampling for unmatched routes
|
||||
```
|
||||
|
||||
### Dynamic Sampling
|
||||
|
||||
Sample based on runtime conditions (user role, request attributes):
|
||||
|
||||
```php app/Http/Middleware/SampleAdminRequests.php
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Laravel\Nightwatch\Facades\Nightwatch;
|
||||
|
||||
class SampleAdminRequests
|
||||
{
|
||||
public function handle(Request $request, Closure $next)
|
||||
{
|
||||
if ($request->user()?->isAdmin()) {
|
||||
Nightwatch::sample(); // Always sample admin requests
|
||||
}
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Command Sampling
|
||||
|
||||
Exclude specific commands from sampling:
|
||||
|
||||
```php AppServiceProvider.php
|
||||
use Illuminate\Console\Events\CommandStarting;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Laravel\Nightwatch\Facades\Nightwatch;
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
Event::listen(function (CommandStarting $event) {
|
||||
if (in_array($event->command, ['schedule:finish', 'horizon:snapshot'])) {
|
||||
Nightwatch::dontSample();
|
||||
}
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### Vendor Commands
|
||||
|
||||
Nightwatch automatically ignores framework/internal commands. Opt-in to capture them:
|
||||
|
||||
```php
|
||||
Nightwatch::captureDefaultVendorCommands();
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Filtering Configuration
|
||||
|
||||
Filtering excludes specific events from collection after sampling. Use filtering to reduce noise and quota usage.
|
||||
|
||||
### Database Queries
|
||||
|
||||
**Filter all queries** (disable query collection):
|
||||
|
||||
```bash
|
||||
NIGHTWATCH_IGNORE_QUERIES=true
|
||||
```
|
||||
|
||||
**Filter specific queries** by SQL pattern:
|
||||
|
||||
```php AppServiceProvider.php
|
||||
use Laravel\Nightwatch\Facades\Nightwatch;
|
||||
use Laravel\Nightwatch\Records\Query;
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
// Filter job table queries (PostgreSQL)
|
||||
Nightwatch::rejectQueries(function (Query $query) {
|
||||
return str_contains($query->sql, 'into "jobs"');
|
||||
});
|
||||
|
||||
// Filter cache table queries (MySQL)
|
||||
Nightwatch::rejectQueries(function (Query $query) {
|
||||
return str_contains($query->sql, 'from `cache`')
|
||||
|| str_contains($query->sql, 'into `cache`');
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### Cache Events
|
||||
|
||||
**Filter all cache events**:
|
||||
|
||||
```bash
|
||||
NIGHTWATCH_IGNORE_CACHE_EVENTS=true
|
||||
```
|
||||
|
||||
**Filter by cache key patterns**:
|
||||
|
||||
```php
|
||||
Nightwatch::rejectCacheKeys([
|
||||
'my-app:users', // Exact match
|
||||
'/^my-app:posts:/', // Regex: starts with my-app:posts:
|
||||
'/^[a-zA-Z0-9]{40}$/', // Regex: session IDs
|
||||
]);
|
||||
```
|
||||
|
||||
**Filter with callback**:
|
||||
|
||||
```php
|
||||
use Laravel\Nightwatch\Records\CacheEvent;
|
||||
|
||||
Nightwatch::rejectCacheEvents(function (CacheEvent $cacheEvent) {
|
||||
return str_starts_with($cacheEvent->key, 'temp:');
|
||||
});
|
||||
```
|
||||
|
||||
### Mail Events
|
||||
|
||||
**Filter all mail**:
|
||||
|
||||
```bash
|
||||
NIGHTWATCH_IGNORE_MAIL=true
|
||||
```
|
||||
|
||||
**Filter specific mail**:
|
||||
|
||||
```php
|
||||
use Laravel\Nightwatch\Records\Mail;
|
||||
|
||||
Nightwatch::rejectMail(function (Mail $mail) {
|
||||
return str_contains($mail->subject, 'Newsletter');
|
||||
});
|
||||
```
|
||||
|
||||
### Notification Events
|
||||
|
||||
**Filter all notifications**:
|
||||
|
||||
```bash
|
||||
NIGHTWATCH_IGNORE_NOTIFICATIONS=true
|
||||
```
|
||||
|
||||
**Filter by channel**:
|
||||
|
||||
```php
|
||||
use Laravel\Nightwatch\Records\Notification;
|
||||
|
||||
Nightwatch::rejectNotifications(function (Notification $notification) {
|
||||
return $notification->channel === 'database';
|
||||
});
|
||||
```
|
||||
|
||||
### Outgoing HTTP Requests
|
||||
|
||||
**Filter all outgoing requests**:
|
||||
|
||||
```bash
|
||||
NIGHTWATCH_IGNORE_OUTGOING_REQUESTS=true
|
||||
```
|
||||
|
||||
**Filter by URL**:
|
||||
|
||||
```php
|
||||
use Laravel\Nightwatch\Records\OutgoingRequest;
|
||||
|
||||
Nightwatch::rejectOutgoingRequests(function (OutgoingRequest $request) {
|
||||
return str_contains($request->url, 'analytics.example.com');
|
||||
});
|
||||
```
|
||||
|
||||
### Queued Jobs
|
||||
|
||||
**Filter specific jobs**:
|
||||
|
||||
```php
|
||||
use Laravel\Nightwatch\Records\QueuedJob;
|
||||
|
||||
Nightwatch::rejectQueuedJobs(function (QueuedJob $job) {
|
||||
return $job->name === 'App\Jobs\LowPriorityJob';
|
||||
});
|
||||
```
|
||||
|
||||
### Decoupling Job Sampling
|
||||
|
||||
Sample jobs independently from parent contexts:
|
||||
|
||||
```php
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
Queue::before(fn () => Nightwatch::sample(rate: 0.5));
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Redaction Configuration
|
||||
|
||||
Redaction modifies captured data to remove or obfuscate sensitive information. Unlike filtering, redaction keeps the event but sanitizes its content.
|
||||
|
||||
### Request Redaction
|
||||
|
||||
**Redact sensitive headers** (automatically redacts: Authorization, Cookie, X-XSRF-TOKEN):
|
||||
|
||||
```bash
|
||||
|
||||
# Customize redacted headers
|
||||
|
||||
NIGHTWATCH_REDACT_HEADERS=Authorization,Cookie,Proxy-Authorization,X-API-Key
|
||||
```
|
||||
|
||||
**Redact request payloads** (disabled by default):
|
||||
|
||||
```bash
|
||||
|
||||
# Enable payload capture
|
||||
|
||||
NIGHTWATCH_CAPTURE_REQUEST_PAYLOAD=true
|
||||
|
||||
# Customize redacted fields
|
||||
|
||||
NIGHTWATCH_REDACT_PAYLOAD_FIELDS=password,password_confirmation,ssn,credit_card
|
||||
```
|
||||
|
||||
**Programmatic redaction**:
|
||||
|
||||
```php
|
||||
use Laravel\Nightwatch\Facades\Nightwatch;
|
||||
use Laravel\Nightwatch\Records\Request;
|
||||
|
||||
Nightwatch::redactRequests(function (Request $request) {
|
||||
$request->url = str_replace('secret', '***', $request->url);
|
||||
$request->ip = preg_replace('/\d+$/', '***', $request->ip);
|
||||
});
|
||||
```
|
||||
|
||||
### Query Redaction
|
||||
|
||||
```php
|
||||
use Laravel\Nightwatch\Records\Query;
|
||||
|
||||
Nightwatch::redactQueries(function (Query $query) {
|
||||
$query->sql = str_replace('secret_token', '***', $query->sql);
|
||||
});
|
||||
```
|
||||
|
||||
### Cache Redaction
|
||||
|
||||
```php
|
||||
use Laravel\Nightwatch\Records\CacheEvent;
|
||||
|
||||
Nightwatch::redactCacheEvents(function (CacheEvent $cacheEvent) {
|
||||
$cacheEvent->key = str_replace('user:', 'user:***:', $cacheEvent->key);
|
||||
});
|
||||
```
|
||||
|
||||
### Command Redaction
|
||||
|
||||
```php
|
||||
use Laravel\Nightwatch\Records\Command;
|
||||
|
||||
Nightwatch::redactCommands(function (Command $command) {
|
||||
$command->command = preg_replace('/--password=\S+/', '--password=***', $command->command);
|
||||
});
|
||||
```
|
||||
|
||||
### Exception Redaction
|
||||
|
||||
```php
|
||||
use Laravel\Nightwatch\Records\Exception;
|
||||
|
||||
Nightwatch::redactExceptions(function (Exception $exception) {
|
||||
$exception->message = str_replace('secret', '***', $exception->message);
|
||||
});
|
||||
```
|
||||
|
||||
### Mail Redaction
|
||||
|
||||
```php
|
||||
use Laravel\Nightwatch\Records\Mail;
|
||||
|
||||
Nightwatch::redactMail(function (Mail $mail) {
|
||||
$mail->subject = str_replace('Invoice #', 'Invoice ***', $mail->subject);
|
||||
});
|
||||
```
|
||||
|
||||
### Outgoing Request Redaction
|
||||
|
||||
```php
|
||||
use Laravel\Nightwatch\Records\OutgoingRequest;
|
||||
|
||||
Nightwatch::redactOutgoingRequests(function (OutgoingRequest $outgoingRequest) {
|
||||
$outgoingRequest->url = preg_replace('/api_key=\w+/', 'api_key=***', $outgoingRequest->url);
|
||||
});
|
||||
```
|
||||
|
|
@ -1,108 +0,0 @@
|
|||
# Nightwatch Configuration Reference
|
||||
|
||||
## Configuration Summary by Event Type
|
||||
|
||||
| Event Type | Sampling | Filtering | Redaction |
|
||||
| --------------------- | -------------------------------------------------- | ---------------------------------------------------------------------------- | ------------------------- |
|
||||
| **Requests** | `NIGHTWATCH_REQUEST_SAMPLE_RATE`, Route middleware | Not applicable | Headers, payload, URL, IP |
|
||||
| **Commands** | `NIGHTWATCH_COMMAND_SAMPLE_RATE`, Event listener | Not applicable | Command arguments |
|
||||
| **Queries** | Parent context | `rejectQueries()`, `NIGHTWATCH_IGNORE_QUERIES` | SQL statement |
|
||||
| **Cache** | Parent context | `rejectCacheKeys()`, `rejectCacheEvents()`, `NIGHTWATCH_IGNORE_CACHE_EVENTS` | Cache key |
|
||||
| **Jobs** | Parent context, Queue::before | `rejectQueuedJobs()` | Not applicable |
|
||||
| **Mail** | Parent context | `rejectMail()`, `NIGHTWATCH_IGNORE_MAIL` | Subject |
|
||||
| **Notifications** | Parent context | `rejectNotifications()`, `NIGHTWATCH_IGNORE_NOTIFICATIONS` | Not applicable |
|
||||
| **Outgoing Requests** | Parent context | `rejectOutgoingRequests()`, `NIGHTWATCH_IGNORE_OUTGOING_REQUESTS` | URL |
|
||||
| **Exceptions** | `NIGHTWATCH_EXCEPTION_SAMPLE_RATE` | Not applicable | Exception message |
|
||||
|
||||
---
|
||||
|
||||
## Production Recommendations
|
||||
|
||||
### High-Traffic Applications
|
||||
|
||||
```bash
|
||||
|
||||
# Conservative sampling
|
||||
|
||||
NIGHTWATCH_REQUEST_SAMPLE_RATE=0.01 # 1% of requests
|
||||
|
||||
NIGHTWATCH_COMMAND_SAMPLE_RATE=0.1 # 10% of commands
|
||||
|
||||
NIGHTWATCH_EXCEPTION_SAMPLE_RATE=1.0 # Always capture exceptions
|
||||
|
||||
# Filter noisy events
|
||||
|
||||
NIGHTWATCH_IGNORE_CACHE_EVENTS=true
|
||||
NIGHTWATCH_IGNORE_QUERIES=true # Or filter specific queries programmatically
|
||||
|
||||
```
|
||||
|
||||
### Privacy-Conscious Applications
|
||||
|
||||
```bash
|
||||
|
||||
# Disable sensitive data collection
|
||||
|
||||
NIGHTWATCH_CAPTURE_REQUEST_PAYLOAD=false
|
||||
NIGHTWATCH_REDACT_HEADERS=Authorization,Cookie,Proxy-Authorization,X-XSRF-TOKEN
|
||||
|
||||
# Or use redaction in AppServiceProvider
|
||||
|
||||
```
|
||||
|
||||
### Balanced Configuration (Recommended Start)
|
||||
|
||||
```bash
|
||||
|
||||
# Sample rates
|
||||
|
||||
NIGHTWATCH_REQUEST_SAMPLE_RATE=0.1
|
||||
NIGHTWATCH_COMMAND_SAMPLE_RATE=1.0
|
||||
NIGHTWATCH_EXCEPTION_SAMPLE_RATE=1.0
|
||||
|
||||
# Filter obvious noise programmatically
|
||||
|
||||
# Redact PII as needed
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Verification Checklist
|
||||
|
||||
After configuration:
|
||||
|
||||
- [ ] Sampling rates appropriate for traffic volume
|
||||
- [ ] Noisy events filtered (cache, certain queries)
|
||||
- [ ] Sensitive data redacted (PII, tokens, credentials)
|
||||
- [ ] Exceptions always captured for debugging
|
||||
- [ ] Test in development with `NIGHTWATCH_REQUEST_SAMPLE_RATE=1.0`
|
||||
- [ ] Monitor event quota usage in Nightwatch dashboard
|
||||
|
||||
---
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Filter Health Checks + Reduce Sampling
|
||||
|
||||
```php
|
||||
Route::get('/health', fn() => ['status' => 'ok'])
|
||||
->middleware(Sample::never());
|
||||
```
|
||||
|
||||
### Exclude Internal/Vendor Queries
|
||||
|
||||
```php
|
||||
Nightwatch::rejectQueries(fn($q) =>
|
||||
str_contains($q->sql, 'telescope') ||
|
||||
str_contains($q->sql, 'pulse')
|
||||
);
|
||||
```
|
||||
|
||||
### Protect User Data in Cache Keys
|
||||
|
||||
```php
|
||||
Nightwatch::redactCacheEvents(fn($e) =>
|
||||
$e->key = preg_replace('/user:\d+/', 'user:***', $e->key)
|
||||
);
|
||||
```
|
||||
|
|
@ -1,85 +0,0 @@
|
|||
---
|
||||
name: configuring-horizon
|
||||
description: "Use this skill whenever the user mentions Horizon by name in a Laravel context. Covers the full Horizon lifecycle: installing Horizon (horizon:install, Sail setup), configuring config/horizon.php (supervisor blocks, queue assignments, balancing strategies, minProcesses/maxProcesses), fixing the dashboard (authorization via Gate::define viewHorizon, blank metrics, horizon:snapshot scheduling), and troubleshooting production issues (worker crashes, timeout chain ordering, LongWaitDetected notifications, waits config). Also covers job tagging and silencing. Do not use for generic Laravel queues without Horizon, SQS or database drivers, standalone Redis setup, Linux supervisord, Telescope, or job batching."
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
|
||||
# Horizon Configuration
|
||||
|
||||
## Documentation
|
||||
|
||||
Use `search-docs` for detailed Horizon patterns and documentation covering configuration, supervisors, balancing, dashboard authorization, tags, notifications, metrics, and deployment.
|
||||
|
||||
For deeper guidance on specific topics, read the relevant reference file before implementing:
|
||||
|
||||
- `references/supervisors.md` covers supervisor blocks, balancing strategies, multi-queue setups, and auto-scaling
|
||||
- `references/notifications.md` covers LongWaitDetected alerts, notification routing, and the `waits` config
|
||||
- `references/tags.md` covers job tagging, dashboard filtering, and silencing noisy jobs
|
||||
- `references/metrics.md` covers the blank metrics dashboard, snapshot scheduling, and retention config
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
php artisan horizon:install
|
||||
```
|
||||
|
||||
### Supervisor Configuration
|
||||
|
||||
Define supervisors in `config/horizon.php`. The `environments` array merges into `defaults` and does not replace the whole supervisor block:
|
||||
|
||||
<!-- Supervisor Config -->
|
||||
```php
|
||||
'defaults' => [
|
||||
'supervisor-1' => [
|
||||
'connection' => 'redis',
|
||||
'queue' => ['default'],
|
||||
'balance' => 'auto',
|
||||
'minProcesses' => 1,
|
||||
'maxProcesses' => 10,
|
||||
'tries' => 3,
|
||||
],
|
||||
],
|
||||
|
||||
'environments' => [
|
||||
'production' => [
|
||||
'supervisor-1' => ['maxProcesses' => 20, 'balanceCooldown' => 3],
|
||||
],
|
||||
'local' => [
|
||||
'supervisor-1' => ['maxProcesses' => 2],
|
||||
],
|
||||
],
|
||||
```
|
||||
|
||||
### Dashboard Authorization
|
||||
|
||||
Restrict access in `App\Providers\HorizonServiceProvider`:
|
||||
|
||||
<!-- Dashboard Gate -->
|
||||
```php
|
||||
protected function gate(): void
|
||||
{
|
||||
Gate::define('viewHorizon', function (User $user) {
|
||||
return $user->is_admin;
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## Verification
|
||||
|
||||
1. Run `php artisan horizon` and visit `/horizon`
|
||||
2. Confirm dashboard access is restricted as expected
|
||||
3. Check that metrics populate after scheduling `horizon:snapshot`
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
- Horizon only works with the Redis queue driver. Other drivers such as database and SQS are not supported.
|
||||
- Redis Cluster is not supported. Horizon requires a standalone Redis connection.
|
||||
- Always check `config/horizon.php` before making changes to understand the current supervisor and environment configuration.
|
||||
- The `environments` array overrides only the keys you specify. It merges into `defaults` and does not replace it.
|
||||
- The timeout chain must be ordered: job `timeout` less than supervisor `timeout` less than `retry_after`. The wrong order can cause jobs to be retried before Horizon finishes timing them out.
|
||||
- The metrics dashboard stays blank until `horizon:snapshot` is scheduled. Running `php artisan horizon` alone does not populate metrics.
|
||||
- Always use `search-docs` for the latest Horizon documentation rather than relying on this skill alone.
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
# Metrics & Snapshots
|
||||
|
||||
## Where to Find It
|
||||
|
||||
Search with `search-docs`:
|
||||
- `"horizon metrics snapshot"` for the snapshot command and scheduling
|
||||
- `"horizon trim snapshots"` for retention configuration
|
||||
|
||||
## What to Watch For
|
||||
|
||||
### Metrics dashboard stays blank until `horizon:snapshot` is scheduled
|
||||
|
||||
Running `horizon` artisan command does not populate metrics automatically. The metrics graph is built from snapshots, so `horizon:snapshot` must be scheduled to run every 5 minutes via Laravel's scheduler.
|
||||
|
||||
### Register the snapshot in the scheduler rather than running it manually
|
||||
|
||||
A single manual run populates the dashboard momentarily but will not keep it updated. Search `"horizon metrics snapshot"` for the exact scheduler registration syntax, which differs between Laravel 10 and 11+.
|
||||
|
||||
### `metrics.trim_snapshots` is a snapshot count, not a time duration
|
||||
|
||||
The `trim_snapshots.job` and `trim_snapshots.queue` values in `config/horizon.php` are counts of snapshots to keep, not minutes or hours. With the default of 24 snapshots at 5-minute intervals, that provides 2 hours of history. Increase the value to retain more history at the cost of Redis memory usage.
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
# Notifications & Alerts
|
||||
|
||||
## Where to Find It
|
||||
|
||||
Search with `search-docs`:
|
||||
- `"horizon notifications"` for Horizon's built-in notification routing helpers
|
||||
- `"horizon long wait detected"` for LongWaitDetected event details
|
||||
|
||||
## What to Watch For
|
||||
|
||||
### `waits` in `config/horizon.php` controls the LongWaitDetected threshold
|
||||
|
||||
The `waits` array (e.g., `'redis:default' => 60`) defines how many seconds a job can wait in a queue before Horizon fires a `LongWaitDetected` event. This value is set in the config file, not in Horizon's notification routing. If alerts are firing too often or too late, adjust `waits` rather than the routing configuration.
|
||||
|
||||
### Use Horizon's built-in notification routing in `HorizonServiceProvider`
|
||||
|
||||
Configure notifications in the `boot()` method of `App\Providers\HorizonServiceProvider` using `Horizon::routeMailNotificationsTo()`, `Horizon::routeSlackNotificationsTo()`, or `Horizon::routeSmsNotificationsTo()`. Horizon already wires `LongWaitDetected` to its notification sender, so the documented setup is notification routing rather than manual listener registration.
|
||||
|
||||
### Failed job alerts are separate from Horizon's documented notification routing
|
||||
|
||||
Horizon's 12.x documentation covers built-in long-wait notifications. Do not assume the docs provide a `JobFailed` listener example in `HorizonServiceProvider`. If a user needs failed job alerts, treat that as custom queue event handling and consult the queue documentation instead of Horizon's notification-routing API.
|
||||
|
|
@ -1,27 +0,0 @@
|
|||
# Supervisor & Balancing Configuration
|
||||
|
||||
## Where to Find It
|
||||
|
||||
Search with `search-docs` before writing any supervisor config, as option names and defaults change between Horizon versions:
|
||||
- `"horizon supervisor configuration"` for the full options list
|
||||
- `"horizon balancing strategies"` for auto, simple, and false modes
|
||||
- `"horizon autoscaling workers"` for autoScalingStrategy details
|
||||
- `"horizon environment configuration"` for the defaults and environments merge
|
||||
|
||||
## What to Watch For
|
||||
|
||||
### The `environments` array merges into `defaults` rather than replacing it
|
||||
|
||||
The `defaults` array defines the complete base supervisor config. The `environments` array patches it per environment, overriding only the keys listed. There is no need to repeat every key in each environment block. A common pattern is to define `connection`, `queue`, `balance`, `autoScalingStrategy`, `tries`, and `timeout` in `defaults`, then override only `maxProcesses`, `balanceMaxShift`, and `balanceCooldown` in `production`.
|
||||
|
||||
### Use separate named supervisors to enforce queue priority
|
||||
|
||||
Horizon does not enforce queue order when using `balance: auto` on a single supervisor. The `queue` array order is ignored for load balancing. To process `notifications` before `default`, use two separately named supervisors: one for the high-priority queue with a higher `maxProcesses`, and one for the low-priority queue with a lower cap. The docs include an explicit note about this.
|
||||
|
||||
### Use `balance: false` to keep a fixed number of workers on a dedicated queue
|
||||
|
||||
Auto-balancing suits variable load, but if a queue should always have exactly N workers such as a video-processing queue limited to 2, set `balance: false` and `maxProcesses: 2`. Auto-balancing would scale it up during bursts, which may be undesirable.
|
||||
|
||||
### Set `balanceCooldown` to prevent rapid worker scaling under bursty load
|
||||
|
||||
When using `balance: auto`, the supervisor can scale up and down rapidly under bursty load. Set `balanceCooldown` to the number of seconds between scaling decisions, typically 3 to 5, to smooth this out. `balanceMaxShift` limits how many processes are added or removed per cycle.
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
# Tags & Silencing
|
||||
|
||||
## Where to Find It
|
||||
|
||||
Search with `search-docs`:
|
||||
- `"horizon tags"` for the tagging API and auto-tagging behaviour
|
||||
- `"horizon silenced jobs"` for the `silenced` and `silenced_tags` config options
|
||||
|
||||
## What to Watch For
|
||||
|
||||
### Eloquent model jobs are tagged automatically without any extra code
|
||||
|
||||
If a job's constructor accepts Eloquent model instances, Horizon automatically tags the job with `ModelClass:id` such as `App\Models\User:42`. These tags are filterable in the dashboard without any changes to the job class. Only add a `tags()` method when custom tags beyond auto-tagging are needed.
|
||||
|
||||
### `silenced` hides jobs from the dashboard completed list but does not stop them from running
|
||||
|
||||
Adding a job class to the `silenced` array in `config/horizon.php` removes it from the completed jobs view. The job still runs normally. This is a dashboard noise-reduction tool, not a way to disable jobs.
|
||||
|
||||
### `silenced_tags` hides all jobs carrying a matching tag from the completed list
|
||||
|
||||
Any job carrying a matching tag string is hidden from the completed jobs view. This is useful for silencing a category of jobs such as all jobs tagged `notifications`, rather than silencing specific classes.
|
||||
|
|
@ -1,575 +0,0 @@
|
|||
---
|
||||
name: inertia-vue-development
|
||||
description: "Develops Inertia.js v3 Vue client-side applications. Activates when creating Vue pages, forms, or navigation; using <Link>, <Form>, useForm, useHttp, setLayoutProps, or router; working with deferred props, prefetching, optimistic updates, instant visits, or polling; or when user mentions Vue with Inertia, Vue pages, Vue forms, or Vue navigation."
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
|
||||
# Inertia Vue Development
|
||||
|
||||
## When to Apply
|
||||
|
||||
Activate this skill when:
|
||||
|
||||
- Creating or modifying Vue page components for Inertia
|
||||
- Working with forms in Vue (using `<Form>`, `useForm`, or `useHttp`)
|
||||
- Implementing client-side navigation with `<Link>` or `router`
|
||||
- Using v3 features: deferred props, prefetching, optimistic updates, instant visits, layout props, HTTP requests, WhenVisible, InfiniteScroll, once props, flash data, or polling
|
||||
- Building Vue-specific features with the Inertia protocol
|
||||
|
||||
## Documentation
|
||||
|
||||
Use `search-docs` for detailed Inertia v3 Vue patterns and documentation.
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### Page Components Location
|
||||
|
||||
Vue page components should be placed in the `resources/js/pages` directory.
|
||||
|
||||
### Page Component Structure
|
||||
|
||||
<!-- Basic Vue Page Component -->
|
||||
```vue
|
||||
<script setup>
|
||||
defineProps({
|
||||
users: Array
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<h1>Users</h1>
|
||||
<ul>
|
||||
<li v-for="user in users" :key="user.id">
|
||||
{{ user.name }}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Client-Side Navigation
|
||||
|
||||
### Basic Link Component
|
||||
|
||||
Use `<Link>` for client-side navigation instead of traditional `<a>` tags:
|
||||
|
||||
<!-- Inertia Vue Navigation -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { Link } from '@inertiajs/vue3'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<Link href="/">Home</Link>
|
||||
<Link href="/users">Users</Link>
|
||||
<Link :href="`/users/${user.id}`">View User</Link>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Link with Method
|
||||
|
||||
<!-- Link with POST Method -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { Link } from '@inertiajs/vue3'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Link href="/logout" method="post" as="button">
|
||||
Logout
|
||||
</Link>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Prefetching
|
||||
|
||||
Prefetch pages to improve perceived performance:
|
||||
|
||||
<!-- Prefetch on Hover -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { Link } from '@inertiajs/vue3'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Link href="/users" prefetch>
|
||||
Users
|
||||
</Link>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Programmatic Navigation
|
||||
|
||||
<!-- Router Visit -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { router } from '@inertiajs/vue3'
|
||||
|
||||
function handleClick() {
|
||||
router.visit('/users')
|
||||
}
|
||||
|
||||
// Or with options
|
||||
function createUser() {
|
||||
router.visit('/users', {
|
||||
method: 'post',
|
||||
data: { name: 'John' },
|
||||
onSuccess: () => console.log('Done'),
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Link href="/users">Users</Link>
|
||||
<Link href="/logout" method="post" as="button">Logout</Link>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Form Handling
|
||||
|
||||
### Form Component (Recommended)
|
||||
|
||||
The recommended way to build forms is with the `<Form>` component:
|
||||
|
||||
<!-- Form Component Example -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { Form } from '@inertiajs/vue3'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Form action="/users" method="post" #default="{ errors, processing, wasSuccessful }">
|
||||
<input type="text" name="name" />
|
||||
<div v-if="errors.name">{{ errors.name }}</div>
|
||||
|
||||
<input type="email" name="email" />
|
||||
<div v-if="errors.email">{{ errors.email }}</div>
|
||||
|
||||
<button type="submit" :disabled="processing">
|
||||
{{ processing ? 'Creating...' : 'Create User' }}
|
||||
</button>
|
||||
|
||||
<div v-if="wasSuccessful">User created!</div>
|
||||
</Form>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Form Component With All Props
|
||||
|
||||
<!-- Form Component Full Example -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { Form } from '@inertiajs/vue3'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Form
|
||||
action="/users"
|
||||
method="post"
|
||||
#default="{
|
||||
errors,
|
||||
hasErrors,
|
||||
processing,
|
||||
progress,
|
||||
wasSuccessful,
|
||||
recentlySuccessful,
|
||||
setError,
|
||||
clearErrors,
|
||||
resetAndClearErrors,
|
||||
defaults,
|
||||
isDirty,
|
||||
reset,
|
||||
submit
|
||||
}"
|
||||
>
|
||||
<input type="text" name="name" :value="defaults.name" />
|
||||
<div v-if="errors.name">{{ errors.name }}</div>
|
||||
|
||||
<button type="submit" :disabled="processing">
|
||||
{{ processing ? 'Saving...' : 'Save' }}
|
||||
</button>
|
||||
|
||||
<progress v-if="progress" :value="progress.percentage" max="100">
|
||||
{{ progress.percentage }}%
|
||||
</progress>
|
||||
|
||||
<div v-if="wasSuccessful">Saved!</div>
|
||||
</Form>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Form Component Reset Props
|
||||
|
||||
The `<Form>` component supports automatic resetting:
|
||||
|
||||
- `resetOnError` - Reset form data when the request fails
|
||||
- `resetOnSuccess` - Reset form data when the request succeeds
|
||||
- `setDefaultsOnSuccess` - Update default values on success
|
||||
|
||||
Use the `search-docs` tool with a query of `form component resetting` for detailed guidance.
|
||||
|
||||
<!-- Form with Reset Props -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { Form } from '@inertiajs/vue3'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Form
|
||||
action="/users"
|
||||
method="post"
|
||||
reset-on-success
|
||||
set-defaults-on-success
|
||||
#default="{ errors, processing, wasSuccessful }"
|
||||
>
|
||||
<input type="text" name="name" />
|
||||
<div v-if="errors.name">{{ errors.name }}</div>
|
||||
|
||||
<button type="submit" :disabled="processing">
|
||||
Submit
|
||||
</button>
|
||||
</Form>
|
||||
</template>
|
||||
```
|
||||
|
||||
Forms can also be built using the `useForm` composable for more programmatic control. Use the `search-docs` tool with a query of `useForm helper` for guidance.
|
||||
|
||||
### `useForm` Composable
|
||||
|
||||
For more programmatic control or to follow existing conventions, use the `useForm` composable:
|
||||
|
||||
<!-- useForm Composable Example -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { useForm } from '@inertiajs/vue3'
|
||||
|
||||
const form = useForm({
|
||||
name: '',
|
||||
email: '',
|
||||
password: '',
|
||||
})
|
||||
|
||||
function submit() {
|
||||
form.post('/users', {
|
||||
onSuccess: () => form.reset('password'),
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<form @submit.prevent="submit">
|
||||
<input type="text" v-model="form.name" />
|
||||
<div v-if="form.errors.name">{{ form.errors.name }}</div>
|
||||
|
||||
<input type="email" v-model="form.email" />
|
||||
<div v-if="form.errors.email">{{ form.errors.email }}</div>
|
||||
|
||||
<input type="password" v-model="form.password" />
|
||||
<div v-if="form.errors.password">{{ form.errors.password }}</div>
|
||||
|
||||
<button type="submit" :disabled="form.processing">
|
||||
Create User
|
||||
</button>
|
||||
</form>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Inertia v3 Features
|
||||
|
||||
### HTTP Requests
|
||||
|
||||
Use the `useHttp` hook for standalone HTTP requests that do not trigger Inertia page visits. It provides the same developer experience as `useForm`, but for plain JSON endpoints.
|
||||
|
||||
<!-- useHttp Example -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { useHttp } from '@inertiajs/vue3'
|
||||
|
||||
const http = useHttp({
|
||||
query: '',
|
||||
})
|
||||
|
||||
function search() {
|
||||
http.get('/api/search', {
|
||||
onSuccess: (response) => {
|
||||
console.log(response)
|
||||
},
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input v-model="http.query" @input="search" />
|
||||
<div v-if="http.processing">Searching...</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Optimistic Updates
|
||||
|
||||
Apply data changes instantly before the server responds, with automatic rollback on failure:
|
||||
|
||||
<!-- Optimistic Update with Router -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { router } from '@inertiajs/vue3'
|
||||
|
||||
function like(post) {
|
||||
router.optimistic((props) => ({
|
||||
post: {
|
||||
...props.post,
|
||||
likes: props.post.likes + 1,
|
||||
},
|
||||
})).post(`/posts/${post.id}/like`)
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
Optimistic updates also work with `useForm` and the `<Form>` component:
|
||||
|
||||
<!-- Optimistic Update with Form Component -->
|
||||
```vue
|
||||
<template>
|
||||
<Form
|
||||
action="/todos"
|
||||
method="post"
|
||||
:optimistic="(props, data) => ({
|
||||
todos: [...props.todos, { id: Date.now(), name: data.name, done: false }],
|
||||
})"
|
||||
>
|
||||
<input type="text" name="name" />
|
||||
<button type="submit">Add Todo</button>
|
||||
</Form>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Instant Visits
|
||||
|
||||
Navigate to a new page immediately without waiting for the server response. The target component renders right away with shared props, while page-specific props load in the background.
|
||||
|
||||
<!-- Instant Visit with Link -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { Link } from '@inertiajs/vue3'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Link href="/dashboard" component="Dashboard">Dashboard</Link>
|
||||
|
||||
<Link
|
||||
href="/posts/1"
|
||||
component="Posts/Show"
|
||||
:page-props="{ post: { id: 1, title: 'My Post' } }"
|
||||
>
|
||||
View Post
|
||||
</Link>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Layout Props
|
||||
|
||||
Share dynamic data between pages and persistent layouts:
|
||||
|
||||
<!-- Layout Props in Layout -->
|
||||
```vue
|
||||
<script setup>
|
||||
withDefaults(defineProps({
|
||||
title: String,
|
||||
showSidebar: Boolean,
|
||||
}), {
|
||||
title: 'My App',
|
||||
showSidebar: true,
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<header>{{ title }}</header>
|
||||
<aside v-if="showSidebar">Sidebar</aside>
|
||||
<main>
|
||||
<slot />
|
||||
</main>
|
||||
</template>
|
||||
```
|
||||
|
||||
<!-- Setting Layout Props from Page -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { setLayoutProps } from '@inertiajs/vue3'
|
||||
|
||||
setLayoutProps({
|
||||
title: 'Dashboard',
|
||||
showSidebar: false,
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<h1>Dashboard</h1>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Deferred Props
|
||||
|
||||
Use deferred props to load data after initial page render:
|
||||
|
||||
<!-- Deferred Props with Empty State -->
|
||||
```vue
|
||||
<script setup>
|
||||
defineProps({
|
||||
users: Array
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<h1>Users</h1>
|
||||
<div v-if="!users" class="animate-pulse">
|
||||
<div class="h-4 bg-gray-200 rounded w-3/4 mb-2"></div>
|
||||
<div class="h-4 bg-gray-200 rounded w-1/2"></div>
|
||||
</div>
|
||||
<ul v-else>
|
||||
<li v-for="user in users" :key="user.id">
|
||||
{{ user.name }}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Polling
|
||||
|
||||
Use the `usePoll` composable to automatically refresh data at intervals. It handles cleanup on unmount and throttles polling when the tab is inactive.
|
||||
|
||||
<!-- Basic Polling -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { usePoll } from '@inertiajs/vue3'
|
||||
|
||||
defineProps({
|
||||
stats: Object
|
||||
})
|
||||
|
||||
usePoll(5000)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<h1>Dashboard</h1>
|
||||
<div>Active Users: {{ stats.activeUsers }}</div>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
<!-- Polling With Request Options and Manual Control -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { usePoll } from '@inertiajs/vue3'
|
||||
|
||||
defineProps({
|
||||
stats: Object
|
||||
})
|
||||
|
||||
const { start, stop } = usePoll(5000, {
|
||||
only: ['stats'],
|
||||
onStart() {
|
||||
console.log('Polling request started')
|
||||
},
|
||||
onFinish() {
|
||||
console.log('Polling request finished')
|
||||
},
|
||||
}, {
|
||||
autoStart: false,
|
||||
keepAlive: true,
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<h1>Dashboard</h1>
|
||||
<div>Active Users: {{ stats.activeUsers }}</div>
|
||||
<button @click="start">Start Polling</button>
|
||||
<button @click="stop">Stop Polling</button>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
- `autoStart` (default `true`) - set to `false` to start polling manually via the returned `start()` function
|
||||
- `keepAlive` (default `false`) - set to `true` to prevent throttling when the browser tab is inactive
|
||||
|
||||
### WhenVisible
|
||||
|
||||
Lazy-load a prop when an element scrolls into view. Useful for deferring expensive data that sits below the fold:
|
||||
|
||||
<!-- WhenVisible Example -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { WhenVisible } from '@inertiajs/vue3'
|
||||
|
||||
defineProps({
|
||||
stats: Object
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<h1>Dashboard</h1>
|
||||
|
||||
<WhenVisible data="stats" :buffer="200">
|
||||
<template #fallback>
|
||||
<div class="animate-pulse">Loading stats...</div>
|
||||
</template>
|
||||
|
||||
<template #default="{ fetching }">
|
||||
<div>
|
||||
<p>Total Users: {{ stats.total_users }}</p>
|
||||
<p>Revenue: {{ stats.revenue }}</p>
|
||||
<span v-if="fetching">Refreshing...</span>
|
||||
</div>
|
||||
</template>
|
||||
</WhenVisible>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
### InfiniteScroll
|
||||
|
||||
Automatically load additional pages of paginated data as users scroll:
|
||||
|
||||
<!-- InfiniteScroll Example -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { InfiniteScroll } from '@inertiajs/vue3'
|
||||
|
||||
defineProps({
|
||||
users: Object
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<InfiniteScroll data="users">
|
||||
<div v-for="user in users.data" :key="user.id">
|
||||
{{ user.name }}
|
||||
</div>
|
||||
</InfiniteScroll>
|
||||
</template>
|
||||
```
|
||||
|
||||
The server must use `Inertia::scroll()` to configure the paginated data. Use the `search-docs` tool with a query of `infinite scroll` for detailed guidance on buffers, manual loading, reverse mode, and custom trigger elements.
|
||||
|
||||
## Server-Side Patterns
|
||||
|
||||
Server-side patterns (Inertia::render, props, middleware) are covered in inertia-laravel guidelines.
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
- Using traditional `<a>` links instead of Inertia's `<Link>` component (breaks SPA behavior)
|
||||
- Forgetting that Vue components must have a single root element
|
||||
- Forgetting to add loading states (skeleton screens) when using deferred props
|
||||
- Not handling the `undefined` state of deferred props before data loads
|
||||
- Using `<form>` without preventing default submission (use `<Form>` component or `@submit.prevent`)
|
||||
- Forgetting to check if `<Form>` component is available in your Inertia version
|
||||
- Using `router.cancel()` instead of `router.cancelAll()` (v3 breaking change)
|
||||
- Using `router.on('invalid', ...)` or `router.on('exception', ...)` instead of the renamed `httpException` and `networkError` events
|
||||
|
|
@ -1,104 +0,0 @@
|
|||
---
|
||||
name: infer-conventions
|
||||
description: "Use this skill to analyze how a Laravel application is actually written and record its conventions as shared rules. Trigger when the user wants to detect, infer, document, or standardize project conventions or coding style, set up or grow `.ai/rules`, resolve mixed or conflicting patterns (e.g. \"are we using Form Requests or inline validation?\"), or onboard agents and teammates to \"how we do things here\". Covers: a systematic sweep of ~49 Laravel convention dimensions (validation, models, architecture, testing, frontend, database, console), open-ended house-pattern discovery, conflict reporting, and recording rules scoped to the right paths via the Boost `record-rule` MCP tool. Do not use for one-off code review, enforcing formatting a linter already handles, or editing `.ai/rules` files by hand."
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
|
||||
# Infer Conventions
|
||||
|
||||
Learn how this application writes Laravel, then record what you learn as durable, path-scoped rules other agents will read. You are documenting reality, not improving it.
|
||||
|
||||
## Ground Rules (read before you start)
|
||||
|
||||
- Consistency first. The codebase's majority style is the convention. Never judge it, never propose a "better" pattern, never record what the code should do. If the app validates inline everywhere, that is the rule, even if Form Requests would be nicer.
|
||||
- Skip what an active tool produces, keep what a tool would fight. Inspect the project's Pint and Rector configuration first; a Rector transformation is tooling-owned only when its package and relevant rule or set are installed and enabled. Active tools may rewrite code toward one canonical form: `$casts` to `casts()`, `$fillable` to attributes, magic accessors to the `Attribute` class, pipe-string rules to arrays, `$signature` to `#[Signature]`, named migrations to anonymous, and many more. When the app already sits at an active tool's target form, the tool owns it, so record nothing. But when the app deliberately holds a form an active tool would refactor away, such as legacy `getXxxAttribute()` accessors the `Attribute` class would replace, no tool can reproduce that choice and an agent defaults the other way. That against-the-grain hold is exactly what to record.
|
||||
- Record decisions, not defaults. A consistent pattern earns a rule only when it reflects a choice: the app took one valid option where the framework or common practice offered others, or the pattern would surprise a competent agent. Framework defaults steer nothing, so skip them: anonymous migrations, `$signature` commands, `ShouldQueue` jobs, `casts()` on Laravel 11+, named routes, Rule objects in `app/Rules`, and `Mail::fake()` or `Bus::fake()` to isolate framework services. A real fork is not enough on its own. Weigh the side the app took, and record only the side an agent would not reach for by itself: inline closures everywhere, legacy accessors, a bespoke query layer. Watch for the false fork too. "No Mockery" next to facade fakes is not a choice against Mockery, because they double different things. The test for every candidate: without this rule, would the next agent plausibly write it differently? Only "yes" earns a rule.
|
||||
- Architecture choices are the gold. Record presence and deliberate absence. The structural pattern the app commits to is the highest-signal convention and the one no tool can decide: Action classes and how they are invoked (`handle` / `execute` / `__invoke`), service objects, dedicated query objects exposing `builder()`, DTOs (spatie/laravel-data vs readonly classes), Form Request validation vs inline, an events and listeners spine vs direct calls, and domain or module folders. Also record a consistent non-pattern, such as "query Eloquent directly in controllers, no repository layer", so the next agent matches the app's altitude instead of over-engineering.
|
||||
- Never duplicate `.ai/rules`. Read `.ai/rules/index.md` and the area files before the sweep. A dimension already covered there is marked done and skipped.
|
||||
- Evidence or silence. A convention needs at least 3 consistent examples and no meaningful rival to become a candidate. Every Step 1 verdict applies this bar.
|
||||
- The recorded rule states the convention, nothing else. One or two imperative lines: this project does X, so do X here. Keep detection evidence out. No counts, ratios, current usage, file lists, or example paths, because that is proof for the confirm step, not part of the rule. One short syntax fragment at most, and point to `search-docs` for API details.
|
||||
|
||||
## Process
|
||||
|
||||
Each step ends on a checkable completion criterion. Do not advance until it holds.
|
||||
|
||||
Fan out when you can. The sweep is embarrassingly parallel. If your environment can spawn subagents (a Task, dispatch, or equivalent tool), do Step 0 yourself, then hand each checklist group (A to J) and the architecture map to its own subagent. Each subagent runs the greps, reads a few representative files, and returns structured verdicts (dimension, verdict, evidence, proposed glob / title / note). You aggregate, dedupe, then run Steps 3 to 5. It is far faster on a real app. No subagents available? Run the steps in sequence, with the same bar and the same output.
|
||||
|
||||
### Step 0: Orient
|
||||
|
||||
Read `composer.json` (installed packages tell you which checklist groups apply), the `pint.json` / PHPStan / Rector config, `.ai/rules/index.md` if present, and most important, map the `app/` tree. List every directory under `app/` (and any `Modules/`, `src/`, `packages/`, or domain root). Every folder beyond Laravel's default skeleton (`Http`, `Models`, `Providers`, `Console`, `Exceptions`) is a structural pattern the app committed to and a high-value rule waiting to be written: `Actions`, `Services`, `Data` or DTOs, `Queries`, `Repositories`, `ViewModels`, `Pipelines`, `Support`, `Enums`, `Contracts`, `Observers`, or `Domain` and module roots. Note each one. You will confirm how it is used in Step 2.
|
||||
|
||||
This app ships a frontend stack, so the frontend checklist group applies. Sweep it.
|
||||
|
||||
Done when: you have the applicable checklist groups, the dimensions already recorded in `.ai/rules`, and a list of every non-default `app/` directory mapped to the pattern it represents.
|
||||
|
||||
### Step 1: Predefined sweep
|
||||
|
||||
Open `references/checklist.md` and work every applicable dimension using its search hints. Give each exactly one verdict:
|
||||
|
||||
- Pattern. Clears the bar, rival under ~20% of sites, and reflects a real choice (passes the decisions-not-defaults test). A recording candidate. Cite 2 to 3 example files.
|
||||
- Conflict. Both styles present in meaningful numbers. Report the split with counts and example files. Never record a preferred winner while the code remains mixed, even in yolo, because that would describe an aspiration rather than reality. Record only if the user identifies a stable path or context boundary that explains both styles; otherwise defer until the code is reconciled.
|
||||
- Default. Consistent, but a framework or common-practice default the agent already writes unprompted. Skip it as a no-op, not a convention.
|
||||
- No signal. Under the bar: feature unused, or too few examples. Skip silently (one summary line at most).
|
||||
- Tooling-owned or Already-recorded. Skip per the ground rules.
|
||||
|
||||
Done when: every applicable dimension carries exactly one of those verdicts.
|
||||
|
||||
### Step 2: Open-ended pass
|
||||
|
||||
First, close out the architecture map from Step 0. For every non-default `app/` directory you listed, confirm how the pattern is used and apply the same evidence and decisions-not-defaults tests as Step 1. Generator-standard or sparsely used directories such as `Rules`, `Observers`, `Mail`, and `Notifications` are signals to inspect, not automatic conventions. Make genuine structural patterns candidates: Action classes invoked via `handle` / `execute` / `__invoke`, Services constructor-injected, `Queries` objects exposing `builder(): Builder`, DTOs as readonly classes or spatie/laravel-data, module or domain folders as the unit of organization. Scope each qualifying pattern to its own directory glob. Also record a consistent deliberate absence, such as "no repository layer, controllers query Eloquent directly", so the next agent matches the app's altitude.
|
||||
|
||||
Then find what else makes this codebase itself: base or abstract classes most code extends, traits used everywhere, tenancy or authorization scoping woven through queries, naming schemes, and custom helpers. Same evidence bar, cite files. Record every genuine structural pattern, and cap the other house findings at ~5 so the pass stays high-signal.
|
||||
|
||||
Done when: every non-default `app/` directory from Step 0 has a verdict, and the pass has produced its cited house findings (or concluded there are none).
|
||||
|
||||
### Step 3: Confirm
|
||||
|
||||
Present every candidate in one batch. Per item: dimension, verdict, evidence (counts and files), and the exact proposed `glob` or `globs` / `title` / `note`. Conflicts are presented as questions about an existing context boundary or deferred cleanup, not as a choice of future style.
|
||||
|
||||
Default mode is confirm: record only what the user approves. Switch to yolo only when the invocation said so ("yolo", "don't ask", "just record them"), then record all pattern candidates without asking. Conflicts still go to the user in yolo.
|
||||
|
||||
Done when: every candidate is approved, rejected, or (conflicts) decided.
|
||||
|
||||
### Step 4: Record
|
||||
|
||||
Make one `record-rule` call for each glob an approved convention applies to. Choose the most specific globs that cover the cited evidence from the mapping table below; if a convention spans models and migrations, record it under both domains so agents discover it from either path. The `note` is the bare convention: strip every trace of detection (see the ground rule). If `record-rule` is unavailable (rules disabled), report the full rule text so the user can enable `BOOST_RULES_ENABLED` or add it by hand.
|
||||
|
||||
Record this:
|
||||
|
||||
> Accessors and mutators: use the legacy magic-method style (`getXxxAttribute()` / `setXxxAttribute()`), not the `Attribute` class. Match it in models.
|
||||
|
||||
Not this:
|
||||
|
||||
> Accessors/mutators use the legacy magic-method style; the `Attribute`-class style is not used anywhere (13 legacy, 0 Attribute-class), e.g. `app/Models/Post.php`. Match the legacy style in existing models.
|
||||
|
||||
Done when: every approved item has a successful tool response, and any failure is reported with its rule text.
|
||||
|
||||
### Step 5: Summarize
|
||||
|
||||
List recorded rules (file and title), conflicts the user deferred, notable no-signals, and remind the user to commit `.ai/rules` so their team and agents share the conventions.
|
||||
|
||||
## Glob mapping
|
||||
|
||||
Attach each rule to the most specific path that covers its evidence. Never a lazy `app/**` when a subtree fits. Match the glob to where the code actually lives, which is not the same in a default skeleton and in a modular or DDD layout. Use the Step 0 `app/` map to pick the real path.
|
||||
|
||||
Examples:
|
||||
|
||||
- Models: `app/Models/**` in a default app, or `app/Modules/Blog/Models/**` / `src/Domain/Blog/**` in a modular one.
|
||||
- Controllers, routing, validation, responses: `app/Http/**`, or `app/Modules/*/Http/**` when each module owns its HTTP layer.
|
||||
- Actions, Services, DTOs: `app/Actions/**`, `app/Services/**`, `app/Data/**`, or the module path the app actually uses.
|
||||
- Tests: `tests/**`.
|
||||
- Migrations and database: `database/migrations/**`.
|
||||
- Truly app-wide (rare, e.g. auth retrieval): `app/**`.
|
||||
|
||||
`record-rule` takes one glob. When a convention genuinely spans two domains (e.g. UUID keys touch models and migrations), call it once per domain with the same title and note; mentioning another path in the note does not make the rule discoverable there.
|
||||
|
||||
## Edge cases
|
||||
|
||||
- Rules disabled or `record-rule` missing: detection is read-only, so Steps 0 to 3 still run, and recording falls back to the manual path in Step 4.
|
||||
- Tiny or fresh app: most dimensions land on no-signal. Say so honestly ("not enough code to infer conventions yet") and record nothing.
|
||||
- Huge app: each dimension is a bounded grep plus a handful of file reads. Sample representative files, do not read everything.
|
||||
- Re-runs: reading `.ai/rules` in Step 0 makes re-runs incremental, so only new or undecided dimensions surface.
|
||||
- Non-standard layout (modules, DDD): the open-ended pass catches the layout itself as convention #1. Adapt the globs in the mapping table to the observed paths.
|
||||
|
|
@ -1,137 +0,0 @@
|
|||
# Detection Checklist
|
||||
|
||||
Every dimension here is a genuine fork: Laravel offers two or more valid approaches, the app's choice changes what the next agent writes, and no active project tool can pick for you. Left out on purpose: pure formatting (Pint owns it), any form an installed and enabled Rector rule rewrites to one canonical shape (`$casts` to `casts()`, `$fillable` to attributes, pipe-string rules to arrays, named to anonymous migrations, `$signature` to `#[Signature]`), and framework defaults any agent writes unprompted (`ShouldQueue` jobs, relation return types, `HasFactory`).
|
||||
|
||||
Each item gives the fork, then a hint (a grep or dir to spot which side the app takes). Hints are only a start. Read the matched files, never record on a raw count. Apply the ground rules to every verdict: a consistent choice that is a default or a tool's target form is not a pattern. Rows tagged (architecture) are the highest-signal, so record presence and deliberate absence.
|
||||
|
||||
---
|
||||
|
||||
## A. Validation & HTTP input
|
||||
|
||||
1. Validation entry point: inline `$request->validate()` vs Form Request classes vs `Validator::make()`.
|
||||
- Hint: `ls app/Http/Requests`; grep `->validate(` / `Validator::make(` in `app/Http/Controllers`.
|
||||
2. Custom rule location: invokable rule objects in `app/Rules` vs inline closures vs `Validator::extend()` in a provider. Rule objects are the default `make:rule` path, so record only if the app leans on closures or `Validator::extend` instead. "No rule objects" alone is just no-signal.
|
||||
- Hint: `ls app/Rules`; grep `Validator::extend` in `app/Providers`.
|
||||
3. Typed input retrieval: typed getters (`$request->string()`, `->integer()`, `->enum()`, `->date()`) vs raw `$request->input()` / dynamic properties.
|
||||
- Hint: grep `->string(` / `->integer(` / `->enum(` vs `->input(` in `app/Http`.
|
||||
4. Custom messages/attributes: `lang/*/validation.php` vs Form Request `messages()` / `attributes()` methods.
|
||||
- Hint: `ls lang`; grep `function messages`, `function attributes` in `app/Http/Requests`.
|
||||
|
||||
## B. Controllers & routing
|
||||
|
||||
5. Controller shape: invokable single-action (`__invoke`) vs resource controllers vs plain multi-method.
|
||||
- Hint: grep `__invoke` in controllers; `Route::resource` / `apiResource` vs verb routes.
|
||||
6. Business-logic location (architecture): fat controllers vs delegated to Actions / Services / Jobs.
|
||||
- Hint: read a few controller methods; `ls app/Actions app/Services`.
|
||||
7. Route handler style: closures in `routes/*.php` vs controller classes.
|
||||
- Hint: count `function ()` vs `::class` in `routes/web.php`, `routes/api.php`.
|
||||
8. Middleware assignment: route/group `->middleware()` vs controller `HasMiddleware::middleware()` vs `#[Middleware]` attribute.
|
||||
- Hint: grep `implements HasMiddleware`, `#[Middleware(` in controllers vs `->middleware(` in routes.
|
||||
9. Route model binding: implicit (type-hinted models) vs explicit `Route::bind` vs manual `findOrFail`.
|
||||
- Hint: typed model params in signatures vs `findOrFail(` in controllers; grep `Route::bind`.
|
||||
10. Rate limiting: named `RateLimiter::for()` + `throttle:name` vs inline `throttle:60,1`.
|
||||
- Hint: grep `RateLimiter::for` in providers vs `throttle:` in route files.
|
||||
|
||||
## C. Authorization
|
||||
|
||||
11. Authorization home: Gates (`Gate::define`) vs Policy classes in `app/Policies`.
|
||||
- Hint: `ls app/Policies`; grep `Gate::define` in `app/Providers`.
|
||||
12. Authorization call site: `$this->authorize()` / `Gate::authorize()` vs `$user->can()` vs `can` middleware vs `#[Authorize]` vs `@can` in Blade.
|
||||
- Hint: grep `authorize(`, `->can(`, `middleware('can:`, `#[Authorize(`, `@can(`.
|
||||
|
||||
## D. Eloquent & models
|
||||
|
||||
13. Mass assignment: `$fillable` allow-list vs `$guarded` block-list.
|
||||
- Hint: grep `protected $fillable` / `protected $guarded` in `app/Models`.
|
||||
14. Accessors/mutators: modern `Attribute` class vs legacy `getXxxAttribute()` / `setXxxAttribute()`. Record a legacy hold, it goes against the tool's grain.
|
||||
- Hint: grep `: Attribute` / `Attribute::make` vs `function get[A-Z].*Attribute` in `app/Models`.
|
||||
15. Primary keys: auto-increment vs `HasUuids` vs `HasUlids`.
|
||||
- Hint: grep `HasUuids` / `HasUlids` in `app/Models`; migration `id()` vs `uuid('id')`.
|
||||
16. Custom casts: dedicated `CastsAttributes` classes (`app/Casts`) vs inline `Attribute` vs built-in cast strings.
|
||||
- Hint: `ls app/Casts`; grep `Cast::class`, `AsStringable::class` in models.
|
||||
17. Data/query layer (architecture): Eloquent directly in controllers vs repositories vs dedicated query objects (e.g. classes exposing `builder(): Builder`).
|
||||
- Hint: `ls app/Repositories app/Queries`; see where non-trivial queries are built.
|
||||
18. Query scopes: local `scope`/`#[Scope]` methods vs dedicated builder classes.
|
||||
- Hint: grep `function scope` / `#[Scope]` in models; `ls app/*/Builders`.
|
||||
19. Model events: observers (`app/Observers`, `#[ObservedBy]`) vs `booted()` closures vs event classes.
|
||||
- Hint: `ls app/Observers`; grep `booted`, `::observe`, `#[ObservedBy]`.
|
||||
20. Eager-load posture: explicit per-query `->with()` vs model-level `$with` defaults. Treat `preventLazyLoading()` separately as a development guard because it can complement either posture.
|
||||
- Hint: grep `protected $with`, `->with(`, and separately `preventLazyLoading` in `app/`.
|
||||
|
||||
## E. Architecture & organization
|
||||
|
||||
21. Action/Service structure (architecture): Action classes (invoked via `handle` / `execute` / `__invoke`) vs service objects vs neither. Cross-check the Step 0 `app/` map: any `Actions`/`Services`/`Pipelines`/`Jobs`-as-actions folder is this pattern, so record how it is invoked.
|
||||
- Hint: `ls app/` (the whole tree, not just `Actions`/`Services`); grep the invocation method in the folder you find.
|
||||
22. DTOs (architecture): spatie/laravel-data vs plain readonly classes vs arrays everywhere.
|
||||
- Hint: `ls app/Data`; grep `extends Data`, `readonly class` in `app/`.
|
||||
23. Dependency acquisition: constructor/method injection vs `app()` / `resolve()` / `App::make()` service location.
|
||||
- Hint: grep `app(` / `resolve(` / `::make(` in `app/` vs promoted constructor deps.
|
||||
24. Decoupling: events + listeners vs direct service calls.
|
||||
- Hint: `ls app/Events app/Listeners`; grep `event(`, `::dispatch(`.
|
||||
25. Helper vs facade idiom: global helpers (`config()`, `auth()`, `response()`) vs facades (`Config::`, `Auth::`, `Response::`).
|
||||
- Hint: ratio of `config(` vs `Config::` (etc.) across `app/`.
|
||||
26. Namespace layout (architecture): default `app/` skeleton vs domain/module folders (`app/Domain/**`, modules).
|
||||
- Hint: `ls app/`, look for `Domain/`, `Modules/`, bounded-context folders.
|
||||
27. Enums: backed vs pure; case naming; where they live.
|
||||
- Hint: `ls app/Enums`; grep `enum .*: string`, `enum .*: int`.
|
||||
|
||||
## F. Frontend & views
|
||||
|
||||
This app ships a frontend stack, so the items below apply.
|
||||
|
||||
28. Frontend stack: Blade+Livewire vs Inertia (Vue/React/Svelte) vs Blade-only / API + separate SPA.
|
||||
- Hint: `composer.json` + `package.json`; `ls resources/js/pages`, `resources/views`.
|
||||
29. Blade composition: class `<x-*>` components vs anonymous components (`@props`) vs `@include` partials.
|
||||
- Hint: `ls app/View/Components`; grep `<x-`, `@include` in `resources/views`.
|
||||
32. Localization: short keys (`lang/*/*.php` + `__('messages.welcome')`) vs JSON string keys (`lang/*.json` + `__('Full sentence')`).
|
||||
- Hint: `ls lang`; grep dotted `__('` vs sentence keys.
|
||||
|
||||
## G. Database & migrations
|
||||
|
||||
33. Foreign keys: `foreignId()->constrained()` vs `foreignIdFor(Model::class)` vs manual `foreign()->references()->on()`.
|
||||
- Hint: grep `foreignId(`, `foreignIdFor(`, `->foreign(` in `database/migrations`.
|
||||
34. `down()` methods: real reverse logic vs omitted / one-way migrations.
|
||||
- Hint: grep `function down` vs the migration count.
|
||||
35. Enum storage: DB `enum()` column vs `string()` + PHP-enum cast on the model.
|
||||
- Hint: grep `->enum(` in migrations vs string columns cast to enums.
|
||||
36. Transactions: `DB::transaction(fn ...)` closure vs manual `beginTransaction` / `commit` / `rollBack`.
|
||||
- Hint: grep `DB::transaction`, `beginTransaction` in `app/`.
|
||||
37. Idempotent writes: `upsert` / `updateOrCreate` / `firstOrCreate` vs find-then-save.
|
||||
- Hint: grep `upsert(`, `updateOrCreate(`, `firstOrCreate(` in `app/`.
|
||||
|
||||
## H. Testing
|
||||
|
||||
38. Framework: Pest (`it()` / `test()` / `expect()`) vs PHPUnit classes.
|
||||
- Hint: `ls tests/Pest.php`; grep `it(` / `test(` vs `extends TestCase`.
|
||||
39. DB reset: `RefreshDatabase` vs `DatabaseTruncation` vs `DatabaseMigrations`.
|
||||
- Hint: grep those trait names in `tests/`.
|
||||
40. Fixtures: compare how equivalent test-owned records are created, such as factories vs manual inserts. Track seeders separately for shared reference data because `$this->seed()` commonly and legitimately coexists with factories.
|
||||
- Hint: grep `::factory(` and direct inserts in `tests/`; separately inspect `$this->seed(` calls and what those seeders provide.
|
||||
41. Collaborator isolation: how the app doubles its own classes, Mockery `mock()` / `spy()` vs real integration. Ignore facade fakes like `Mail::fake()` here, they isolate framework services by default and are not a fork against Mockery.
|
||||
- Hint: grep `->mock(`, `->spy(`, `Mockery::` in `tests/`.
|
||||
42. Endpoint assertions: array `assertJson([...])` / `assertJsonFragment` vs fluent `AssertableJson`.
|
||||
- Hint: grep `AssertableJson`, `assertJsonFragment` in `tests/`.
|
||||
|
||||
## I. Responses & API resources
|
||||
|
||||
43. Response shape: API Resource classes vs `response()->json()` vs returning models/arrays directly.
|
||||
- Hint: `ls app/Http/Resources`; grep `JsonResource`, `->json(` in controllers.
|
||||
44. Resource relationship inclusion: `whenLoaded()` guards vs unconditional relationship access. Do not count ordinary scalar attributes as rivals to conditional relationships, and evaluate general `when()` fields separately.
|
||||
- Hint: compare relationship fields using `whenLoaded(` with unconditional relationship property access in `app/Http/Resources`.
|
||||
45. Pagination contracts: within comparable endpoint categories, length-aware `paginate()` vs `simplePaginate()` vs `cursorPaginate()`. These have different totals, navigation, ordering, and performance contracts, so record only a stable path-scoped API policy, never a project-wide majority.
|
||||
- Hint: grep those in `app/`, then group matches by endpoint type and client contract before comparing them.
|
||||
46. Web redirects/URLs: `route('name')` vs `url('/path')` vs `action([...])`.
|
||||
- Hint: grep `route('`, `url('/`, `action([` in `app/Http` and views.
|
||||
|
||||
## J. Strings, collections & dates
|
||||
|
||||
47. Iteration idiom: `collect()->map()->filter()` pipelines vs `array_map` / `foreach`.
|
||||
- Hint: grep `collect(`, `->map(` vs `array_map`, `foreach` density in `app/`.
|
||||
48. String API: fluent `Str::of()->...` (Stringable) vs static `Str::` vs native (`trim`, `strtoupper`).
|
||||
- Hint: grep `Str::of(` vs `Str::` vs native string funcs.
|
||||
49. Dates: compare equivalent construction call styles (`now()` / `today()` helpers vs `Carbon::`) separately from the application's mutable/immutable date policy. `Date::use(CarbonImmutable::class)` can make helpers return immutable dates, so those signals are complementary rather than conflicting.
|
||||
- Hint: grep `now(` and `Carbon::` for call style; separately inspect `CarbonImmutable` and `Date::use` for mutability policy.
|
||||
|
||||
---
|
||||
|
||||
Genuine forks only. Every row survived the "no tool can decide this, and it isn't the default" filter. Give each applicable dimension exactly one verdict: pattern, conflict, default, no-signal, tooling-owned, or already-recorded. The rows tagged (architecture) are where the highest-value rules come from.
|
||||
|
|
@ -1,59 +0,0 @@
|
|||
---
|
||||
name: laravel-best-practices
|
||||
description: "Apply this skill whenever writing, reviewing, or refactoring Laravel PHP code. This includes creating or modifying controllers, models, migrations, form requests, policies, jobs, scheduled commands, service classes, and Eloquent queries. Triggers for N+1 and query performance issues, caching strategies, authorization and security patterns, validation, error handling, queue and job configuration, route definitions, and architectural decisions. Also use for Laravel code reviews and refactoring existing Laravel code to follow best practices. Covers any task involving Laravel backend PHP code patterns."
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
|
||||
# Laravel Best Practices
|
||||
|
||||
Best practices for Laravel, organized as an index of rule files. Each rule file teaches what to do and why. For exact API syntax, verify with `search-docs`.
|
||||
|
||||
## Consistency First
|
||||
|
||||
Before applying any rule, check what the application already does. Laravel offers multiple valid approaches, and the best choice is the one the codebase already uses, even if another pattern would be theoretically better. Inconsistency is worse than a suboptimal pattern.
|
||||
|
||||
Check sibling files, related controllers, models, or tests for established patterns. If one exists, follow it. Don't introduce a second way. These rules are defaults for when no pattern exists yet, not overrides.
|
||||
|
||||
## How to Apply
|
||||
|
||||
1. Check the changed files, nearby code, project configuration, and relevant tests for established patterns. Deviate only for a correctness or security defect, and call the deviation out.
|
||||
2. Map every affected concern to the rule index below. Read each mapped rule file before editing. Skip unrelated rule files.
|
||||
3. Make the smallest coherent change. Keep the application's architecture and naming instead of introducing a second pattern for the same job.
|
||||
4. Verify version-sensitive Laravel APIs for the installed version with `search-docs`, or inspect the installed framework when it is unavailable.
|
||||
5. Run the narrowest relevant tests first, then the project's formatting and static-analysis checks when the change warrants them.
|
||||
6. Re-read the diff against every mapped rule before finishing.
|
||||
|
||||
## Rule Index
|
||||
|
||||
Cross-cutting changes often need more than one rule file.
|
||||
|
||||
| Concern | Read |
|
||||
| --- | --- |
|
||||
| Query count, eager loading, indexes, large datasets | [`rules/db-performance.md`](rules/db-performance.md) |
|
||||
| Subqueries, aggregates, complex ordering and query plans | [`rules/advanced-queries.md`](rules/advanced-queries.md) |
|
||||
| Models, relationships, scopes, casts | [`rules/eloquent.md`](rules/eloquent.md) |
|
||||
| Authentication, authorization, input safety, secrets, uploads | [`rules/security.md`](rules/security.md) |
|
||||
| Form Requests and validation rules | [`rules/validation.md`](rules/validation.md) |
|
||||
| Controllers, route binding, resources, middleware | [`rules/routing.md`](rules/routing.md) |
|
||||
| Schema changes, columns, foreign keys, indexes | [`rules/migrations.md`](rules/migrations.md) |
|
||||
| Jobs, retries, uniqueness, batches, Horizon | [`rules/queue-jobs.md`](rules/queue-jobs.md) |
|
||||
| Cache lifetime, invalidation, locks, memoization | [`rules/caching.md`](rules/caching.md) |
|
||||
| Outbound requests, retries, timeouts, fakes | [`rules/http-client.md`](rules/http-client.md) |
|
||||
| Exceptions, reporting, rendering, log context | [`rules/error-handling.md`](rules/error-handling.md) |
|
||||
| Events and notifications | [`rules/events-notifications.md`](rules/events-notifications.md) |
|
||||
| Mailables and mail assertions | [`rules/mail.md`](rules/mail.md) |
|
||||
| Scheduled tasks and overlap protection | [`rules/scheduling.md`](rules/scheduling.md) |
|
||||
| Collections, lazy iteration, bulk operations | [`rules/collections.md`](rules/collections.md) |
|
||||
| Blade components, attributes, composers | [`rules/blade-views.md`](rules/blade-views.md) |
|
||||
| Environment values and application configuration | [`rules/config.md`](rules/config.md) |
|
||||
| Pest/PHPUnit patterns, factories, fakes | [`rules/testing.md`](rules/testing.md) |
|
||||
| Naming, helpers, file boundaries, PHP style | [`rules/style.md`](rules/style.md) |
|
||||
| Actions, services, dependencies, application structure | [`rules/architecture.md`](rules/architecture.md) |
|
||||
|
||||
## Decision Rules
|
||||
|
||||
- Prefer framework features and existing application abstractions over new helpers or dependencies.
|
||||
- Avoid speculative abstractions. Extract code when it creates a clear domain boundary, removes meaningful duplication, or makes behavior independently testable.
|
||||
- Keep database access out of Blade views and prevent hidden N+1 queries across controllers, resources, jobs, and serialization.
|
||||
|
|
@ -1,106 +0,0 @@
|
|||
# Advanced Query Patterns
|
||||
|
||||
## Use `addSelect()` Subqueries for Single Values from Has-Many
|
||||
|
||||
Instead of eager-loading an entire has-many relationship for a single value (like the latest timestamp), use a correlated subquery via `addSelect()`. This pulls the value directly in the main SQL query — zero extra queries.
|
||||
|
||||
```php
|
||||
public function scopeWithLastLoginAt($query): void
|
||||
{
|
||||
$query->addSelect([
|
||||
'last_login_at' => Login::select('created_at')
|
||||
->whereColumn('user_id', 'users.id')
|
||||
->latest()
|
||||
->take(1),
|
||||
])->withCasts(['last_login_at' => 'datetime']);
|
||||
}
|
||||
```
|
||||
|
||||
## Create Dynamic Relationships via Subquery FK
|
||||
|
||||
Extend the `addSelect()` pattern to fetch a foreign key via subquery, then define a `belongsTo` relationship on that virtual attribute. This provides a fully-hydrated related model without loading the entire collection.
|
||||
|
||||
```php
|
||||
public function lastLogin(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Login::class);
|
||||
}
|
||||
|
||||
public function scopeWithLastLogin($query): void
|
||||
{
|
||||
$query->addSelect([
|
||||
'last_login_id' => Login::select('id')
|
||||
->whereColumn('user_id', 'users.id')
|
||||
->latest()
|
||||
->take(1),
|
||||
])->with('lastLogin');
|
||||
}
|
||||
```
|
||||
|
||||
## Use Conditional Aggregates Instead of Multiple Count Queries
|
||||
|
||||
Replace N separate `count()` queries with a single query using `CASE WHEN` inside `selectRaw()`. Use `toBase()` to skip model hydration when you only need scalar values.
|
||||
|
||||
```php
|
||||
$statuses = Feature::toBase()
|
||||
->selectRaw("count(case when status = 'Requested' then 1 end) as requested")
|
||||
->selectRaw("count(case when status = 'Planned' then 1 end) as planned")
|
||||
->selectRaw("count(case when status = 'Completed' then 1 end) as completed")
|
||||
->first();
|
||||
```
|
||||
|
||||
## Use `setRelation()` to Prevent Circular N+1
|
||||
|
||||
When a parent model is eager-loaded with its children, and the view also needs `$child->parent`, use `setRelation()` to inject the already-loaded parent rather than letting Eloquent fire N additional queries.
|
||||
|
||||
```php
|
||||
$feature->load('comments.user');
|
||||
$feature->comments->each->setRelation('feature', $feature);
|
||||
```
|
||||
|
||||
## Prefer `whereIn` + Subquery Over `whereHas`
|
||||
|
||||
`whereHas()` emits a correlated `EXISTS` subquery that re-executes per row. Using `whereIn()` with a `select('id')` subquery lets the database use an index lookup instead, without loading data into PHP memory.
|
||||
|
||||
Incorrect (correlated EXISTS re-executes per row):
|
||||
|
||||
```php
|
||||
$query->whereHas('company', fn ($q) => $q->where('name', 'like', $term));
|
||||
```
|
||||
|
||||
Correct (index-friendly subquery, no PHP memory overhead):
|
||||
|
||||
```php
|
||||
$query->whereIn('company_id', Company::where('name', 'like', $term)->select('id'));
|
||||
```
|
||||
|
||||
## Sometimes Two Simple Queries Beat One Complex Query
|
||||
|
||||
Running a small, targeted secondary query and passing its results via `whereIn` is often faster than a single complex correlated subquery or join. The additional round-trip is worthwhile when the secondary query is highly selective and uses its own index.
|
||||
|
||||
## Use Compound Indexes Matching `orderBy` Column Order
|
||||
|
||||
When ordering by multiple columns, create a single compound index in the same column order as the `ORDER BY` clause. Individual single-column indexes cannot combine for multi-column sorts — the database will filesort without a compound index.
|
||||
|
||||
```php
|
||||
// Migration
|
||||
$table->index(['last_name', 'first_name']);
|
||||
|
||||
// Query — column order must match the index
|
||||
User::query()->orderBy('last_name')->orderBy('first_name')->paginate();
|
||||
```
|
||||
|
||||
## Use Correlated Subqueries for Has-Many Ordering
|
||||
|
||||
When sorting by a value from a has-many relationship, avoid joins (they duplicate rows). Use a correlated subquery inside `orderBy()` instead, paired with an `addSelect` scope for eager loading.
|
||||
|
||||
```php
|
||||
public function scopeOrderByLastLogin($query): void
|
||||
{
|
||||
$query->orderByDesc(Login::select('created_at')
|
||||
->whereColumn('user_id', 'users.id')
|
||||
->latest()
|
||||
->take(1)
|
||||
);
|
||||
}
|
||||
```
|
||||
|
|
@ -1,202 +0,0 @@
|
|||
# Architecture Best Practices
|
||||
|
||||
## Single-Purpose Action Classes
|
||||
|
||||
Extract discrete business operations into invokable Action classes.
|
||||
|
||||
```php
|
||||
class CreateOrderAction
|
||||
{
|
||||
public function __construct(private InventoryService $inventory) {}
|
||||
|
||||
public function handle(array $data): Order
|
||||
{
|
||||
$order = Order::create($data);
|
||||
$this->inventory->reserve($order);
|
||||
|
||||
return $order;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Use Dependency Injection
|
||||
|
||||
Always use constructor injection. Avoid `app()` or `resolve()` inside classes.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
class OrderController extends Controller
|
||||
{
|
||||
public function store(StoreOrderRequest $request)
|
||||
{
|
||||
$service = app(OrderService::class);
|
||||
|
||||
return $service->create($request->validated());
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
class OrderController extends Controller
|
||||
{
|
||||
public function __construct(private OrderService $service) {}
|
||||
|
||||
public function store(StoreOrderRequest $request)
|
||||
{
|
||||
return $this->service->create($request->validated());
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Code to Interfaces
|
||||
|
||||
Depend on contracts at system boundaries (payment gateways, notification channels, external APIs) for testability and swappability.
|
||||
|
||||
Incorrect (concrete dependency):
|
||||
```php
|
||||
class OrderService
|
||||
{
|
||||
public function __construct(private StripeGateway $gateway) {}
|
||||
}
|
||||
```
|
||||
|
||||
Correct (interface dependency):
|
||||
```php
|
||||
interface PaymentGateway
|
||||
{
|
||||
public function charge(int $amount, string $customerId): PaymentResult;
|
||||
}
|
||||
|
||||
class OrderService
|
||||
{
|
||||
public function __construct(private PaymentGateway $gateway) {}
|
||||
}
|
||||
```
|
||||
|
||||
Bind in a service provider:
|
||||
|
||||
```php
|
||||
$this->app->bind(PaymentGateway::class, StripeGateway::class);
|
||||
```
|
||||
|
||||
## Default Sort by Descending
|
||||
|
||||
When no explicit order is specified, sort by `id` or `created_at` descending. Without an explicit `ORDER BY`, row order is undefined.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
$posts = Post::paginate();
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
$posts = Post::latest()->paginate();
|
||||
```
|
||||
|
||||
## Use Atomic Locks for Race Conditions
|
||||
|
||||
Prevent race conditions with `Cache::lock()` or `lockForUpdate()`.
|
||||
|
||||
```php
|
||||
Cache::lock('order-processing-'.$order->id, 10)->block(5, function () use ($order) {
|
||||
$order->process();
|
||||
});
|
||||
|
||||
// Or at query level
|
||||
$product = Product::where('id', $id)->lockForUpdate()->first();
|
||||
```
|
||||
|
||||
## Use `mb_*` String Functions
|
||||
|
||||
When no Laravel helper exists, prefer `mb_strlen`, `mb_strtolower`, etc. for UTF-8 safety. Standard PHP string functions count bytes, not characters.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
strlen('José'); // 5 (bytes, not characters)
|
||||
strtolower('MÜNCHEN'); // 'mÜnchen' — fails on multibyte
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
mb_strlen('José'); // 4 (characters)
|
||||
mb_strtolower('MÜNCHEN'); // 'münchen'
|
||||
|
||||
// Prefer Laravel's Str helpers when available
|
||||
Str::length('José'); // 4
|
||||
Str::lower('MÜNCHEN'); // 'münchen'
|
||||
```
|
||||
|
||||
## Use `defer()` for Post-Response Work
|
||||
|
||||
For lightweight tasks that don't need to survive a crash (logging, analytics, cleanup), use `defer()` instead of dispatching a job. The callback runs after the HTTP response is sent — no queue overhead.
|
||||
|
||||
Incorrect (job overhead for trivial work):
|
||||
```php
|
||||
dispatch(new LogPageView($page));
|
||||
```
|
||||
|
||||
Correct (runs after response, same process):
|
||||
```php
|
||||
defer(fn () => PageView::create(['page_id' => $page->id, 'user_id' => auth()->id()]));
|
||||
```
|
||||
|
||||
Use jobs when the work must survive process crashes or needs retry logic. Use `defer()` for fire-and-forget work.
|
||||
|
||||
## Use `Context` for Request-Scoped Data
|
||||
|
||||
The `Context` facade passes data through the entire request lifecycle — middleware, controllers, jobs, logs — without passing arguments manually.
|
||||
|
||||
```php
|
||||
// In middleware
|
||||
Context::add('tenant_id', $request->header('X-Tenant-ID'));
|
||||
|
||||
// Anywhere later — controllers, jobs, log context
|
||||
$tenantId = Context::get('tenant_id');
|
||||
```
|
||||
|
||||
Context data automatically propagates to queued jobs and is included in log entries. Use `Context::addHidden()` for sensitive data that should be available in queued jobs but excluded from log context. If data must not leave the current process, do not store it in `Context`.
|
||||
|
||||
## Use `Concurrency::run()` for Parallel Execution
|
||||
|
||||
Run independent operations in parallel using child processes — no async libraries needed.
|
||||
|
||||
```php
|
||||
use Illuminate\Support\Facades\Concurrency;
|
||||
|
||||
[$users, $orders] = Concurrency::run([
|
||||
fn () => User::count(),
|
||||
fn () => Order::where('status', 'pending')->count(),
|
||||
]);
|
||||
```
|
||||
|
||||
Each closure runs in a separate process with full Laravel access. Use for independent database queries, API calls, or computations that would otherwise run sequentially.
|
||||
|
||||
## Convention Over Configuration
|
||||
|
||||
Follow Laravel conventions. Don't override defaults unnecessarily.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
class Customer extends Model
|
||||
{
|
||||
protected $table = 'Customer';
|
||||
protected $primaryKey = 'customer_id';
|
||||
|
||||
public function roles(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Role::class, 'role_customer', 'customer_id', 'role_id');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
class Customer extends Model
|
||||
{
|
||||
public function roles(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Role::class);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
|
@ -1,36 +0,0 @@
|
|||
# Blade & Views Best Practices
|
||||
|
||||
## Use `$attributes->merge()` in Component Templates
|
||||
|
||||
Hardcoding classes prevents consumers from adding their own. `merge()` combines class attributes cleanly.
|
||||
|
||||
```blade
|
||||
<div {{ $attributes->merge(['class' => 'alert alert-'.$type]) }}>
|
||||
{{ $message }}
|
||||
</div>
|
||||
```
|
||||
|
||||
## Use `@pushOnce` for Per-Component Scripts
|
||||
|
||||
If a component renders inside a `@foreach`, `@push` inserts the script N times. `@pushOnce` guarantees it's included exactly once.
|
||||
|
||||
## Prefer Blade Components Over `@include`
|
||||
|
||||
`@include` shares all parent variables implicitly (hidden coupling). Components have explicit props, attribute bags, and slots.
|
||||
|
||||
## Use View Composers for Shared View Data
|
||||
|
||||
If every controller rendering a sidebar must pass `$categories`, that's duplicated code. A View Composer centralizes it.
|
||||
|
||||
## Use Blade Fragments for Partial Re-Renders (htmx/Turbo)
|
||||
|
||||
A single view can return either the full page or just a fragment, keeping routing clean.
|
||||
|
||||
```php
|
||||
return view('dashboard', compact('users'))
|
||||
->fragmentIf($request->hasHeader('HX-Request'), 'user-list');
|
||||
```
|
||||
|
||||
## Use `@aware` for Deeply Nested Component Props
|
||||
|
||||
Avoids re-passing parent props through every level of nested components.
|
||||
|
|
@ -1,70 +0,0 @@
|
|||
# Caching Best Practices
|
||||
|
||||
## Use `Cache::remember()` Instead of Manual Get/Put
|
||||
|
||||
Cleaner cache-aside pattern that removes boilerplate. use `Cache::lock()` for race conditions.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
$val = Cache::get('stats');
|
||||
if (! $val) {
|
||||
$val = $this->computeStats();
|
||||
Cache::put('stats', $val, 60);
|
||||
}
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
$val = Cache::remember('stats', 60, fn () => $this->computeStats());
|
||||
```
|
||||
|
||||
## Use `Cache::flexible()` for Stale-While-Revalidate
|
||||
|
||||
On high-traffic keys, one user always gets a slow response when the cache expires. `flexible()` serves slightly stale data while refreshing in the background.
|
||||
|
||||
Incorrect: `Cache::remember('users', 300, fn () => User::all());`
|
||||
|
||||
Correct: `Cache::flexible('users', [300, 600], fn () => User::all());` — fresh for 5 min, stale-but-served up to 10 min, refreshes via deferred function.
|
||||
|
||||
## Use `Cache::memo()` to Avoid Redundant Hits Within a Request
|
||||
|
||||
If the same cache key is read multiple times per request (e.g., a service called from multiple places), `memo()` stores the resolved value in memory.
|
||||
|
||||
`Cache::memo()->get('settings');` — 5 calls = 1 Redis round-trip instead of 5.
|
||||
|
||||
## Use Cache Tags to Invalidate Related Groups
|
||||
|
||||
Without tags, invalidating a group of entries requires tracking every key. Tags let you flush atomically. Only works with `redis`, `memcached`, `dynamodb` — not `file` or `database`.
|
||||
|
||||
```php
|
||||
Cache::tags(['user-1'])->flush();
|
||||
```
|
||||
|
||||
## Use `Cache::add()` for Atomic Conditional Writes
|
||||
|
||||
`add()` only writes if the key does not exist — atomic, no race condition between checking and writing.
|
||||
|
||||
Incorrect: `if (! Cache::has('lock')) { Cache::put('lock', true, 10); }`
|
||||
|
||||
Correct: `Cache::add('lock', true, 10);`
|
||||
|
||||
## Use `once()` for Per-Request Memoization
|
||||
|
||||
`once()` memoizes a function's return value for the lifetime of the object (or request for closures). Unlike `Cache::memo()`, it doesn't hit the cache store at all — pure in-memory.
|
||||
|
||||
```php
|
||||
public function roles(): Collection
|
||||
{
|
||||
return once(fn () => $this->loadRoles());
|
||||
}
|
||||
```
|
||||
|
||||
Multiple calls return the cached result without re-executing. Use `once()` for expensive computations called multiple times per request. Use `Cache::memo()` when you also want cross-request caching.
|
||||
|
||||
## Configure Failover Cache Stores in Production
|
||||
|
||||
If Redis goes down, the app falls back to a secondary store automatically.
|
||||
|
||||
```php
|
||||
'failover' => ['driver' => 'failover', 'stores' => ['redis', 'database']],
|
||||
```
|
||||
|
|
@ -1,44 +0,0 @@
|
|||
# Collection Best Practices
|
||||
|
||||
## Use Higher-Order Messages for Simple Operations
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
$users->each(function (User $user) {
|
||||
$user->markAsVip();
|
||||
});
|
||||
```
|
||||
|
||||
Correct: `$users->each->markAsVip();`
|
||||
|
||||
Works with `each`, `map`, `sum`, `filter`, `reject`, `contains`, etc.
|
||||
|
||||
## Choose `cursor()` vs. `lazy()` Correctly
|
||||
|
||||
- `cursor()` — one model in memory, but cannot eager-load relationships (N+1 risk).
|
||||
- `lazy()` — chunked pagination returning a flat LazyCollection, supports eager loading.
|
||||
|
||||
Incorrect: `User::with('roles')->cursor()` — eager loading silently ignored.
|
||||
|
||||
Correct: `User::with('roles')->lazy()` for relationship access; `User::cursor()` for attribute-only work.
|
||||
|
||||
## Use `lazyById()` When Updating Records While Iterating
|
||||
|
||||
`lazy()` uses offset pagination — updating records during iteration can skip or double-process. `lazyById()` uses `id > last_id`, safe against mutation.
|
||||
|
||||
## Use `toQuery()` for Bulk Operations on Collections
|
||||
|
||||
Avoids manual `whereIn` construction.
|
||||
|
||||
Incorrect: `User::whereIn('id', $users->pluck('id'))->update([...]);`
|
||||
|
||||
Correct: `$users->toQuery()->update([...]);`
|
||||
|
||||
## Use `#[CollectedBy]` for Custom Collection Classes
|
||||
|
||||
More declarative than overriding `newCollection()`.
|
||||
|
||||
```php
|
||||
#[CollectedBy(UserCollection::class)]
|
||||
class User extends Model {}
|
||||
```
|
||||
|
|
@ -1,73 +0,0 @@
|
|||
# Configuration Best Practices
|
||||
|
||||
## `env()` Only in Config Files
|
||||
|
||||
Direct `env()` calls may return `null` when config is cached.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
$key = env('API_KEY');
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
// config/services.php
|
||||
'key' => env('API_KEY'),
|
||||
|
||||
// Application code
|
||||
$key = config('services.key');
|
||||
```
|
||||
|
||||
## Use Encrypted Env or External Secrets
|
||||
|
||||
Never store production secrets in plain `.env` files in version control.
|
||||
|
||||
Incorrect:
|
||||
```bash
|
||||
|
||||
# .env committed to repo or shared in Slack
|
||||
|
||||
STRIPE_SECRET=sk_live_abc123
|
||||
AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI
|
||||
```
|
||||
|
||||
Correct:
|
||||
```bash
|
||||
php artisan env:encrypt --env=production --readable
|
||||
php artisan env:decrypt --env=production
|
||||
```
|
||||
|
||||
For cloud deployments, prefer the platform's native secret store (AWS Secrets Manager, Vault, etc.) and inject at runtime.
|
||||
|
||||
## Use `App::environment()` for Environment Checks
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
if (env('APP_ENV') === 'production') {
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
if (app()->isProduction()) {
|
||||
// or
|
||||
if (App::environment('production')) {
|
||||
```
|
||||
|
||||
## Use Constants and Language Files
|
||||
|
||||
Use class constants instead of hardcoded magic strings for model states, types, and statuses.
|
||||
|
||||
```php
|
||||
// Incorrect
|
||||
return $this->type === 'normal';
|
||||
|
||||
// Correct
|
||||
return $this->type === self::TYPE_NORMAL;
|
||||
```
|
||||
|
||||
If the application already uses language files for localization, use `__()` for user-facing strings too. Do not introduce language files purely for English-only apps — simple string literals are fine there.
|
||||
|
||||
```php
|
||||
// Only when lang files already exist in the project
|
||||
return back()->with('message', __('app.article_added'));
|
||||
```
|
||||
|
|
@ -1,192 +0,0 @@
|
|||
# Database Performance Best Practices
|
||||
|
||||
## Always Eager Load Relationships
|
||||
|
||||
Lazy loading causes N+1 query problems — one query per loop iteration. Always use `with()` to load relationships upfront.
|
||||
|
||||
Incorrect (N+1 — executes 1 + N queries):
|
||||
```php
|
||||
$posts = Post::all();
|
||||
foreach ($posts as $post) {
|
||||
echo $post->author->name;
|
||||
}
|
||||
```
|
||||
|
||||
Correct (2 queries total):
|
||||
```php
|
||||
$posts = Post::with('author')->get();
|
||||
foreach ($posts as $post) {
|
||||
echo $post->author->name;
|
||||
}
|
||||
```
|
||||
|
||||
Constrain eager loads to select only needed columns (always include the foreign key):
|
||||
|
||||
```php
|
||||
$users = User::with(['posts' => function ($query) {
|
||||
$query->select('id', 'user_id', 'title')
|
||||
->where('published', true)
|
||||
->latest()
|
||||
->limit(10);
|
||||
}])->get();
|
||||
```
|
||||
|
||||
## Prevent Lazy Loading in Development
|
||||
|
||||
Enable this in `AppServiceProvider::boot()` to catch N+1 issues during development.
|
||||
|
||||
```php
|
||||
public function boot(): void
|
||||
{
|
||||
Model::preventLazyLoading(! app()->isProduction());
|
||||
}
|
||||
```
|
||||
|
||||
Throws `LazyLoadingViolationException` when a relationship is accessed without being eager-loaded.
|
||||
|
||||
## Select Only Needed Columns
|
||||
|
||||
Avoid `SELECT *` — especially when tables have large text or JSON columns.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
$posts = Post::with('author')->get();
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
$posts = Post::select('id', 'title', 'user_id', 'created_at')
|
||||
->with(['author:id,name,avatar'])
|
||||
->get();
|
||||
```
|
||||
|
||||
When selecting columns on eager-loaded relationships, always include the foreign key column or the relationship won't match.
|
||||
|
||||
## Chunk Large Datasets
|
||||
|
||||
Never load thousands of records at once. Use chunking for batch processing.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
$users = User::all();
|
||||
foreach ($users as $user) {
|
||||
$user->notify(new WeeklyDigest);
|
||||
}
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
User::where('subscribed', true)->chunk(200, function ($users) {
|
||||
foreach ($users as $user) {
|
||||
$user->notify(new WeeklyDigest);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
Use `chunkById()` when modifying records during iteration — standard `chunk()` uses OFFSET which shifts when rows change:
|
||||
|
||||
```php
|
||||
User::where('active', false)->chunkById(200, function ($users) {
|
||||
$users->each->delete();
|
||||
});
|
||||
```
|
||||
|
||||
## Add Database Indexes
|
||||
|
||||
Index columns that appear in `WHERE`, `ORDER BY`, `JOIN`, and `GROUP BY` clauses.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
Schema::create('orders', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('user_id')->constrained();
|
||||
$table->string('status');
|
||||
$table->timestamps();
|
||||
});
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
Schema::create('orders', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('user_id')->index()->constrained();
|
||||
$table->string('status')->index();
|
||||
$table->timestamps();
|
||||
$table->index(['status', 'created_at']);
|
||||
});
|
||||
```
|
||||
|
||||
Add composite indexes for common query patterns (e.g., `WHERE status = ? ORDER BY created_at`).
|
||||
|
||||
## Use `withCount()` for Counting Relations
|
||||
|
||||
Never load entire collections just to count them.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
$posts = Post::all();
|
||||
foreach ($posts as $post) {
|
||||
echo $post->comments->count();
|
||||
}
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
$posts = Post::withCount('comments')->get();
|
||||
foreach ($posts as $post) {
|
||||
echo $post->comments_count;
|
||||
}
|
||||
```
|
||||
|
||||
Conditional counting:
|
||||
|
||||
```php
|
||||
$posts = Post::withCount([
|
||||
'comments',
|
||||
'comments as approved_comments_count' => function ($query) {
|
||||
$query->where('approved', true);
|
||||
},
|
||||
])->get();
|
||||
```
|
||||
|
||||
## Use `cursor()` for Memory-Efficient Iteration
|
||||
|
||||
For read-only iteration over large result sets, `cursor()` loads one record at a time via a PHP generator.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
$users = User::where('active', true)->get();
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
foreach (User::where('active', true)->cursor() as $user) {
|
||||
ProcessUser::dispatch($user->id);
|
||||
}
|
||||
```
|
||||
|
||||
Use `cursor()` for read-only iteration. Use `chunk()` / `chunkById()` when modifying records.
|
||||
|
||||
## No Queries in Blade Templates
|
||||
|
||||
Never execute queries in Blade templates. Pass data from controllers.
|
||||
|
||||
Incorrect:
|
||||
```blade
|
||||
@foreach (User::all() as $user)
|
||||
{{ $user->profile->name }}
|
||||
@endforeach
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
// Controller
|
||||
$users = User::with('profile')->get();
|
||||
return view('users.index', compact('users'));
|
||||
```
|
||||
|
||||
```blade
|
||||
@foreach ($users as $user)
|
||||
{{ $user->profile->name }}
|
||||
@endforeach
|
||||
```
|
||||
|
|
@ -1,150 +0,0 @@
|
|||
# Eloquent Best Practices
|
||||
|
||||
## Use Correct Relationship Types
|
||||
|
||||
Use `hasMany`, `belongsTo`, `morphMany`, etc. with proper return type hints.
|
||||
|
||||
```php
|
||||
public function comments(): HasMany
|
||||
{
|
||||
return $this->hasMany(Comment::class);
|
||||
}
|
||||
|
||||
public function author(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'user_id');
|
||||
}
|
||||
```
|
||||
|
||||
## Use Local Scopes for Reusable Queries
|
||||
|
||||
Extract reusable query constraints into local scopes to avoid duplication.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
$active = User::where('verified', true)->whereNotNull('activated_at')->get();
|
||||
$articles = Article::whereHas('user', function ($q) {
|
||||
$q->where('verified', true)->whereNotNull('activated_at');
|
||||
})->get();
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
#[Scope]
|
||||
protected function active(Builder $query): Builder
|
||||
{
|
||||
return $query->where('verified', true)->whereNotNull('activated_at');
|
||||
}
|
||||
|
||||
// Usage
|
||||
$active = User::active()->get();
|
||||
$articles = Article::whereHas('user', fn ($q) => $q->active())->get();
|
||||
```
|
||||
|
||||
## Apply Global Scopes Sparingly
|
||||
|
||||
Global scopes silently modify every query on the model, making debugging difficult. Prefer local scopes and reserve global scopes for truly universal constraints like soft deletes or multi-tenancy.
|
||||
|
||||
Incorrect (global scope for a conditional filter):
|
||||
```php
|
||||
class PublishedScope implements Scope
|
||||
{
|
||||
public function apply(Builder $builder, Model $model): void
|
||||
{
|
||||
$builder->where('published', true);
|
||||
}
|
||||
}
|
||||
// Now admin panels, reports, and background jobs all silently skip drafts
|
||||
```
|
||||
|
||||
Correct (local scope you opt into):
|
||||
```php
|
||||
#[Scope]
|
||||
protected function published(Builder $query): Builder
|
||||
{
|
||||
return $query->where('published', true);
|
||||
}
|
||||
|
||||
Post::published()->paginate(); // Explicit
|
||||
Post::paginate(); // Admin sees all
|
||||
```
|
||||
|
||||
## Define Attribute Casts
|
||||
|
||||
Use the `casts()` method (or `$casts` property following project convention) for automatic type conversion.
|
||||
|
||||
```php
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'is_active' => 'boolean',
|
||||
'metadata' => 'array',
|
||||
'total' => 'decimal:2',
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
## Cast Date Columns Properly
|
||||
|
||||
Always cast date columns. Use Carbon instances in templates instead of formatting strings manually.
|
||||
|
||||
Incorrect:
|
||||
```blade
|
||||
{{ Carbon::createFromFormat('Y-d-m H-i', $order->ordered_at)->toDateString() }}
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'ordered_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
```blade
|
||||
{{ $order->ordered_at->toDateString() }}
|
||||
{{ $order->ordered_at->format('m-d') }}
|
||||
```
|
||||
|
||||
## Use `whereBelongsTo()` for Relationship Queries
|
||||
|
||||
Cleaner than manually specifying foreign keys.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
Post::where('user_id', $user->id)->get();
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
Post::whereBelongsTo($user)->get();
|
||||
Post::whereBelongsTo($user, 'author')->get();
|
||||
```
|
||||
|
||||
## Avoid Hardcoded Table Names in Queries
|
||||
|
||||
Never use string literals for table names in raw queries, joins, or subqueries. Hardcoded table names make it impossible to find all places a model is used and break refactoring (e.g., renaming a table requires hunting through every raw string).
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
DB::table('users')->where('active', true)->get();
|
||||
|
||||
$query->join('companies', 'companies.id', '=', 'users.company_id');
|
||||
|
||||
DB::select('SELECT * FROM orders WHERE status = ?', ['pending']);
|
||||
```
|
||||
|
||||
Correct — reference the model's table:
|
||||
```php
|
||||
DB::table((new User)->getTable())->where('active', true)->get();
|
||||
|
||||
// Even better — use Eloquent or the query builder instead of raw SQL
|
||||
User::where('active', true)->get();
|
||||
Order::where('status', 'pending')->get();
|
||||
```
|
||||
|
||||
Prefer Eloquent queries and relationships over `DB::table()` whenever possible — they already reference the model's table. When `DB::table()` or raw joins are unavoidable, always use `(new Model)->getTable()` to keep the reference traceable.
|
||||
|
||||
**Exception — migrations:** In migrations, hardcoded table names via `DB::table('settings')` are acceptable and preferred. Models change over time but migrations are frozen snapshots — referencing a model that is later renamed or deleted would break the migration.
|
||||
|
|
@ -1,72 +0,0 @@
|
|||
# Error Handling Best Practices
|
||||
|
||||
## Exception Reporting and Rendering
|
||||
|
||||
There are two valid approaches — choose one and apply it consistently across the project.
|
||||
|
||||
**Co-location on the exception class** — keeps behavior alongside the exception definition, easier to find:
|
||||
|
||||
```php
|
||||
class InvalidOrderException extends Exception
|
||||
{
|
||||
public function report(): void { /* custom reporting */ }
|
||||
|
||||
public function render(Request $request): Response
|
||||
{
|
||||
return response()->view('errors.invalid-order', status: 422);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Centralized in `bootstrap/app.php`** — all exception handling in one place, easier to see the full picture:
|
||||
|
||||
```php
|
||||
->withExceptions(function (Exceptions $exceptions) {
|
||||
$exceptions->report(function (InvalidOrderException $e) { /* ... */ });
|
||||
$exceptions->render(function (InvalidOrderException $e, Request $request) {
|
||||
return response()->view('errors.invalid-order', status: 422);
|
||||
});
|
||||
})
|
||||
```
|
||||
|
||||
Check the existing codebase and follow whichever pattern is already established.
|
||||
|
||||
## Use `ShouldntReport` for Exceptions That Should Never Log
|
||||
|
||||
More discoverable than listing classes in `dontReport()`.
|
||||
|
||||
```php
|
||||
class PodcastProcessingException extends Exception implements ShouldntReport {}
|
||||
```
|
||||
|
||||
## Throttle High-Volume Exceptions
|
||||
|
||||
A single failing integration can flood error tracking. Use `throttle()` to rate-limit per exception type.
|
||||
|
||||
## Enable `dontReportDuplicates()`
|
||||
|
||||
Prevents the same exception instance from being logged multiple times when `report($e)` is called in multiple catch blocks.
|
||||
|
||||
## Force JSON Error Rendering for API Routes
|
||||
|
||||
Laravel auto-detects `Accept: application/json` but API clients may not set it. Explicitly declare JSON rendering for API routes.
|
||||
|
||||
```php
|
||||
$exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) {
|
||||
return $request->is('api/*') || $request->expectsJson();
|
||||
});
|
||||
```
|
||||
|
||||
## Add Context to Exception Classes
|
||||
|
||||
Attach structured data to exceptions at the source via a `context()` method — Laravel includes it automatically in the log entry.
|
||||
|
||||
```php
|
||||
class InvalidOrderException extends Exception
|
||||
{
|
||||
public function context(): array
|
||||
{
|
||||
return ['order_id' => $this->orderId];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
|
@ -1,52 +0,0 @@
|
|||
# Events & Notifications Best Practices
|
||||
|
||||
## Rely on Event Discovery
|
||||
|
||||
Laravel auto-discovers listeners by reading `handle(EventType $event)` type-hints. No manual registration needed in `AppServiceProvider`.
|
||||
|
||||
## Run `event:cache` in Production Deploy
|
||||
|
||||
Event discovery scans the filesystem per-request in dev. Cache it in production: `php artisan optimize` or `php artisan event:cache`.
|
||||
|
||||
## Use `ShouldDispatchAfterCommit` Inside Transactions
|
||||
|
||||
Without it, a queued listener may process before the DB transaction commits, reading data that doesn't exist yet.
|
||||
|
||||
```php
|
||||
class OrderShipped implements ShouldDispatchAfterCommit {}
|
||||
```
|
||||
|
||||
## Always Queue Notifications
|
||||
|
||||
Notifications often hit external APIs (email, SMS, Slack). Without `ShouldQueue`, they block the HTTP response.
|
||||
|
||||
```php
|
||||
class InvoicePaid extends Notification implements ShouldQueue
|
||||
{
|
||||
use Queueable;
|
||||
}
|
||||
```
|
||||
|
||||
## Use `afterCommit()` on Notifications in Transactions
|
||||
|
||||
Same race condition as events — call `afterCommit()` to delay dispatch until the transaction commits.
|
||||
|
||||
```php
|
||||
$user->notify((new InvoicePaid($invoice))->afterCommit());
|
||||
```
|
||||
|
||||
## Route Notification Channels to Dedicated Queues
|
||||
|
||||
Mail and database notifications have different priorities. Use `viaQueues()` to route them to separate queues.
|
||||
|
||||
## Use On-Demand Notifications for Non-User Recipients
|
||||
|
||||
Avoid creating dummy models to send notifications to arbitrary addresses.
|
||||
|
||||
```php
|
||||
Notification::route('mail', 'admin@example.com')->notify(new SystemAlert());
|
||||
```
|
||||
|
||||
## Implement `HasLocalePreference` on Notifiable Models
|
||||
|
||||
Laravel automatically uses the user's preferred locale for all notifications and mailables — no per-call `locale()` needed.
|
||||
|
|
@ -1,160 +0,0 @@
|
|||
# HTTP Client Best Practices
|
||||
|
||||
## Always Set Explicit Timeouts
|
||||
|
||||
The default timeout is 30 seconds — too long for most API calls. Always set explicit `timeout` and `connectTimeout` to fail fast.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
$response = Http::get('https://api.example.com/users');
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
$response = Http::timeout(5)
|
||||
->connectTimeout(3)
|
||||
->get('https://api.example.com/users');
|
||||
```
|
||||
|
||||
For service-specific clients, define timeouts in a macro:
|
||||
|
||||
```php
|
||||
Http::macro('github', function () {
|
||||
return Http::baseUrl('https://api.github.com')
|
||||
->timeout(10)
|
||||
->connectTimeout(3)
|
||||
->withToken(config('services.github.token'));
|
||||
});
|
||||
|
||||
$response = Http::github()->get('/repos/laravel/framework');
|
||||
```
|
||||
|
||||
## Use Retry with Backoff for External APIs
|
||||
|
||||
External APIs have transient failures. Use `retry()` with increasing delays.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
$response = Http::post('https://api.stripe.com/v1/charges', $data);
|
||||
|
||||
if ($response->failed()) {
|
||||
throw new PaymentFailedException('Charge failed');
|
||||
}
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
$response = Http::retry([100, 500, 1000])
|
||||
->timeout(10)
|
||||
->post('https://api.stripe.com/v1/charges', $data);
|
||||
```
|
||||
|
||||
Only retry on specific errors:
|
||||
|
||||
```php
|
||||
$response = Http::retry(3, 100, function (Throwable $exception, PendingRequest $request) {
|
||||
return $exception instanceof ConnectionException
|
||||
|| ($exception instanceof RequestException && $exception->response->serverError());
|
||||
})->post('https://api.example.com/data');
|
||||
```
|
||||
|
||||
## Handle Errors Explicitly
|
||||
|
||||
The HTTP Client does not throw on 4xx/5xx by default. Always check status or use `throw()`.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
$response = Http::get('https://api.example.com/users/1');
|
||||
$user = $response->json(); // Could be an error body
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
$response = Http::timeout(5)
|
||||
->get('https://api.example.com/users/1')
|
||||
->throw();
|
||||
|
||||
$user = $response->json();
|
||||
```
|
||||
|
||||
For graceful degradation:
|
||||
|
||||
```php
|
||||
$response = Http::get('https://api.example.com/users/1');
|
||||
|
||||
if ($response->successful()) {
|
||||
return $response->json();
|
||||
}
|
||||
|
||||
if ($response->notFound()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$response->throw();
|
||||
```
|
||||
|
||||
## Use Request Pooling for Concurrent Requests
|
||||
|
||||
When making multiple independent API calls, use `Http::pool()` instead of sequential calls.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
$users = Http::get('https://api.example.com/users')->json();
|
||||
$posts = Http::get('https://api.example.com/posts')->json();
|
||||
$comments = Http::get('https://api.example.com/comments')->json();
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
use Illuminate\Http\Client\Pool;
|
||||
|
||||
$responses = Http::pool(fn (Pool $pool) => [
|
||||
$pool->as('users')->get('https://api.example.com/users'),
|
||||
$pool->as('posts')->get('https://api.example.com/posts'),
|
||||
$pool->as('comments')->get('https://api.example.com/comments'),
|
||||
]);
|
||||
|
||||
$users = $responses['users']->json();
|
||||
$posts = $responses['posts']->json();
|
||||
```
|
||||
|
||||
## Fake HTTP Calls in Tests
|
||||
|
||||
Never make real HTTP requests in tests. Use `Http::fake()` and `preventStrayRequests()`.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
it('syncs user from API', function () {
|
||||
$service = new UserSyncService;
|
||||
$service->sync(1); // Hits the real API
|
||||
});
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
it('syncs user from API', function () {
|
||||
Http::preventStrayRequests();
|
||||
|
||||
Http::fake([
|
||||
'api.example.com/users/1' => Http::response([
|
||||
'name' => 'John Doe',
|
||||
'email' => 'john@example.com',
|
||||
]),
|
||||
]);
|
||||
|
||||
$service = new UserSyncService;
|
||||
$service->sync(1);
|
||||
|
||||
Http::assertSent(function (Request $request) {
|
||||
return $request->url() === 'https://api.example.com/users/1';
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
Test failure scenarios too:
|
||||
|
||||
```php
|
||||
Http::fake([
|
||||
'api.example.com/*' => Http::failedConnection(),
|
||||
]);
|
||||
```
|
||||
|
|
@ -1,27 +0,0 @@
|
|||
# Mail Best Practices
|
||||
|
||||
## Implement `ShouldQueue` on the Mailable Class
|
||||
|
||||
Makes queueing the default regardless of how the mailable is dispatched. No need to remember `Mail::queue()` at every call site — `Mail::send()` also queues it.
|
||||
|
||||
## Use `afterCommit()` on Mailables Inside Transactions
|
||||
|
||||
A queued mailable dispatched inside a transaction may process before the commit. Use `$this->afterCommit()` in the constructor.
|
||||
|
||||
## Use `assertQueued()` Not `assertSent()` for Queued Mailables
|
||||
|
||||
`Mail::assertSent()` only catches synchronous mail. Queued mailables fail `assertSent` with a "Did you mean to use assertQueued()?" hint.
|
||||
|
||||
Incorrect: `Mail::assertSent(OrderShipped::class);` when mailable implements `ShouldQueue`.
|
||||
|
||||
Correct: `Mail::assertQueued(OrderShipped::class);`
|
||||
|
||||
## Use Markdown Mailables for Transactional Emails
|
||||
|
||||
Markdown mailables auto-generate both HTML and plain-text versions, use responsive components, and allow global style customization. Generate with `--markdown` flag.
|
||||
|
||||
## Separate Content Tests from Sending Tests
|
||||
|
||||
Content tests: instantiate the mailable directly, call `assertSeeInHtml()`.
|
||||
Sending tests: use `Mail::fake()` and `assertSent()`/`assertQueued()`.
|
||||
Don't mix them — it conflates concerns and makes tests brittle.
|
||||
|
|
@ -1,121 +0,0 @@
|
|||
# Migration Best Practices
|
||||
|
||||
## Generate Migrations with Artisan
|
||||
|
||||
Always use `php artisan make:migration` for consistent naming and timestamps.
|
||||
|
||||
Incorrect (manually created file):
|
||||
```php
|
||||
// database/migrations/posts_migration.php ← wrong naming, no timestamp
|
||||
```
|
||||
|
||||
Correct (Artisan-generated):
|
||||
```bash
|
||||
php artisan make:migration create_posts_table
|
||||
php artisan make:migration add_slug_to_posts_table
|
||||
```
|
||||
|
||||
## Use `constrained()` for Foreign Keys
|
||||
|
||||
Automatic naming and referential integrity.
|
||||
|
||||
```php
|
||||
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
|
||||
|
||||
// Non-standard names
|
||||
$table->foreignId('author_id')->constrained('users');
|
||||
```
|
||||
|
||||
## Never Modify Deployed Migrations
|
||||
|
||||
Once a migration has run in production, treat it as immutable. Create a new migration to change the table.
|
||||
|
||||
Incorrect (editing a deployed migration):
|
||||
```php
|
||||
// 2024_01_01_create_posts_table.php — already in production
|
||||
$table->string('slug')->unique(); // ← added after deployment
|
||||
```
|
||||
|
||||
Correct (new migration to alter):
|
||||
```php
|
||||
// 2024_03_15_add_slug_to_posts_table.php
|
||||
Schema::table('posts', function (Blueprint $table) {
|
||||
$table->string('slug')->unique()->after('title');
|
||||
});
|
||||
```
|
||||
|
||||
## Add Indexes in the Migration
|
||||
|
||||
Add indexes when creating the table, not as an afterthought. Columns used in `WHERE`, `ORDER BY`, and `JOIN` clauses need indexes.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
Schema::create('orders', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('user_id')->constrained();
|
||||
$table->string('status');
|
||||
$table->timestamps();
|
||||
});
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
Schema::create('orders', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('user_id')->constrained()->index();
|
||||
$table->string('status')->index();
|
||||
$table->timestamp('shipped_at')->nullable()->index();
|
||||
$table->timestamps();
|
||||
});
|
||||
```
|
||||
|
||||
## Mirror Defaults in Model `$attributes`
|
||||
|
||||
When a column has a database default, mirror it in the model so new instances have correct values before saving.
|
||||
|
||||
```php
|
||||
// Migration
|
||||
$table->string('status')->default('pending');
|
||||
|
||||
// Model
|
||||
protected $attributes = [
|
||||
'status' => 'pending',
|
||||
];
|
||||
```
|
||||
|
||||
## Write Reversible `down()` Methods by Default
|
||||
|
||||
Implement `down()` for schema changes that can be safely reversed so `migrate:rollback` works in CI and failed deployments.
|
||||
|
||||
```php
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('posts', function (Blueprint $table) {
|
||||
$table->dropColumn('slug');
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
For intentionally irreversible migrations (e.g., destructive data backfills), leave a clear comment and require a forward fix migration instead of pretending rollback is supported.
|
||||
|
||||
## Keep Migrations Focused
|
||||
|
||||
One concern per migration. Never mix DDL (schema changes) and DML (data manipulation).
|
||||
|
||||
Incorrect (partial failure creates unrecoverable state):
|
||||
```php
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('settings', function (Blueprint $table) { ... });
|
||||
DB::table('settings')->insert(['key' => 'version', 'value' => '1.0']);
|
||||
}
|
||||
```
|
||||
|
||||
Correct (separate migrations):
|
||||
```php
|
||||
// Migration 1: create_settings_table
|
||||
Schema::create('settings', function (Blueprint $table) { ... });
|
||||
|
||||
// Migration 2: seed_default_settings
|
||||
DB::table('settings')->insert(['key' => 'version', 'value' => '1.0']);
|
||||
```
|
||||
|
|
@ -1,144 +0,0 @@
|
|||
# Queue & Job Best Practices
|
||||
|
||||
## Set `retry_after` Greater Than `timeout`
|
||||
|
||||
If `retry_after` is shorter than the job's `timeout`, the queue worker re-dispatches the job while it's still running, causing duplicate execution.
|
||||
|
||||
Incorrect (`retry_after` ≤ `timeout`):
|
||||
```php
|
||||
class ProcessReport implements ShouldQueue
|
||||
{
|
||||
public $timeout = 120;
|
||||
}
|
||||
|
||||
// config/queue.php — retry_after: 90 ← job retried while still running!
|
||||
```
|
||||
|
||||
Correct (`retry_after` > `timeout`):
|
||||
```php
|
||||
class ProcessReport implements ShouldQueue
|
||||
{
|
||||
public $timeout = 120;
|
||||
}
|
||||
|
||||
// config/queue.php — retry_after: 180 ← safely longer than any job timeout
|
||||
```
|
||||
|
||||
## Use Exponential Backoff
|
||||
|
||||
Use progressively longer delays between retries to avoid hammering failing services.
|
||||
|
||||
Incorrect (fixed retry interval):
|
||||
```php
|
||||
class SyncWithStripe implements ShouldQueue
|
||||
{
|
||||
public $tries = 3;
|
||||
// Default: retries immediately, overwhelming the API
|
||||
}
|
||||
```
|
||||
|
||||
Correct (exponential backoff):
|
||||
```php
|
||||
class SyncWithStripe implements ShouldQueue
|
||||
{
|
||||
public $tries = 3;
|
||||
public $backoff = [1, 5, 10];
|
||||
}
|
||||
```
|
||||
|
||||
## Implement `ShouldBeUnique`
|
||||
|
||||
Prevent duplicate job processing.
|
||||
|
||||
```php
|
||||
class GenerateInvoice implements ShouldQueue, ShouldBeUnique
|
||||
{
|
||||
public function uniqueId(): string
|
||||
{
|
||||
return $this->order->id;
|
||||
}
|
||||
|
||||
public $uniqueFor = 3600;
|
||||
}
|
||||
```
|
||||
|
||||
## Always Implement `failed()`
|
||||
|
||||
Handle errors explicitly — don't rely on silent failure.
|
||||
|
||||
```php
|
||||
public function failed(?Throwable $exception): void
|
||||
{
|
||||
$this->podcast->update(['status' => 'failed']);
|
||||
Log::error('Processing failed', ['id' => $this->podcast->id, 'error' => $exception->getMessage()]);
|
||||
}
|
||||
```
|
||||
|
||||
## Rate Limit External API Calls in Jobs
|
||||
|
||||
Use `RateLimited` middleware to throttle jobs calling third-party APIs.
|
||||
|
||||
```php
|
||||
public function middleware(): array
|
||||
{
|
||||
return [new RateLimited('external-api')];
|
||||
}
|
||||
```
|
||||
|
||||
## Batch Related Jobs
|
||||
|
||||
Use `Bus::batch()` when jobs should succeed or fail together.
|
||||
|
||||
```php
|
||||
Bus::batch([
|
||||
new ImportCsvChunk($chunk1),
|
||||
new ImportCsvChunk($chunk2),
|
||||
])
|
||||
->then(fn (Batch $batch) => Notification::send($user, new ImportComplete))
|
||||
->catch(fn (Batch $batch, Throwable $e) => Log::error('Batch failed'))
|
||||
->dispatch();
|
||||
```
|
||||
|
||||
## `retryUntil()` Needs `$tries = 0`
|
||||
|
||||
When using time-based retry limits, set `$tries = 0` to avoid premature failure.
|
||||
|
||||
```php
|
||||
public $tries = 0;
|
||||
|
||||
public function retryUntil(): \DateTimeInterface
|
||||
{
|
||||
return now()->addHours(4);
|
||||
}
|
||||
```
|
||||
|
||||
## Use `ShouldBeUniqueUntilProcessing` for Early Lock Release
|
||||
|
||||
`ShouldBeUnique` holds the lock until the job completes. `ShouldBeUniqueUntilProcessing` releases it when processing starts, allowing new instances to queue.
|
||||
|
||||
```php
|
||||
class UpdateSearchIndex implements ShouldQueue, ShouldBeUniqueUntilProcessing
|
||||
{
|
||||
// Lock releases when processing begins, not when it finishes
|
||||
}
|
||||
```
|
||||
|
||||
## Use Horizon for Complex Queue Scenarios
|
||||
|
||||
Use Laravel Horizon when you need monitoring, auto-scaling, failure tracking, or multiple queues with different priorities.
|
||||
|
||||
```php
|
||||
// config/horizon.php
|
||||
'environments' => [
|
||||
'production' => [
|
||||
'supervisor-1' => [
|
||||
'connection' => 'redis',
|
||||
'queue' => ['high', 'default', 'low'],
|
||||
'balance' => 'auto',
|
||||
'minProcesses' => 1,
|
||||
'maxProcesses' => 10,
|
||||
'tries' => 3,
|
||||
],
|
||||
],
|
||||
],
|
||||
```
|
||||
|
|
@ -1,99 +0,0 @@
|
|||
# Routing & Controllers Best Practices
|
||||
|
||||
## Use Implicit Route Model Binding
|
||||
|
||||
Let Laravel resolve models automatically from route parameters.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
public function show(int $id)
|
||||
{
|
||||
$post = Post::findOrFail($id);
|
||||
}
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
public function show(Post $post)
|
||||
{
|
||||
return view('posts.show', ['post' => $post]);
|
||||
}
|
||||
```
|
||||
|
||||
## Use Scoped Bindings for Nested Resources
|
||||
|
||||
Enforce parent-child relationships automatically.
|
||||
|
||||
```php
|
||||
Route::get('/users/{user}/posts/{post}', function (User $user, Post $post) {
|
||||
// $post is automatically scoped to $user
|
||||
})->scopeBindings();
|
||||
```
|
||||
|
||||
## Use Resource Controllers
|
||||
|
||||
Use `Route::resource()` or `apiResource()` for RESTful endpoints.
|
||||
|
||||
```php
|
||||
Route::resource('posts', PostController::class);
|
||||
// In routes/api.php — the /api prefix is applied automatically
|
||||
Route::apiResource('posts', Api\PostController::class);
|
||||
```
|
||||
|
||||
## Keep Controllers Thin
|
||||
|
||||
Aim for under 10 lines per method. Extract business logic to action or service classes.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
public function store(Request $request)
|
||||
{
|
||||
$validated = $request->validate([...]);
|
||||
if ($request->hasFile('image')) {
|
||||
$request->file('image')->move(public_path('images'));
|
||||
}
|
||||
$post = Post::create($validated);
|
||||
$post->tags()->sync($validated['tags']);
|
||||
event(new PostCreated($post));
|
||||
return redirect()->route('posts.show', $post);
|
||||
}
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
public function store(StorePostRequest $request, CreatePostAction $create)
|
||||
{
|
||||
$post = $create->execute($request->validated());
|
||||
|
||||
return redirect()->route('posts.show', $post);
|
||||
}
|
||||
```
|
||||
|
||||
## Type-Hint Form Requests
|
||||
|
||||
Type-hinting Form Requests triggers automatic validation and authorization before the method executes.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'title' => ['required', 'max:255'],
|
||||
'body' => ['required'],
|
||||
]);
|
||||
|
||||
Post::create($validated);
|
||||
|
||||
return redirect()->route('posts.index');
|
||||
}
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
public function store(StorePostRequest $request): RedirectResponse
|
||||
{
|
||||
Post::create($request->validated());
|
||||
|
||||
return redirect()->route('posts.index');
|
||||
}
|
||||
```
|
||||
|
|
@ -1,39 +0,0 @@
|
|||
# Task Scheduling Best Practices
|
||||
|
||||
## Use `withoutOverlapping()` on Variable-Duration Tasks
|
||||
|
||||
Without it, a long-running task spawns a second instance on the next tick, causing double-processing or resource exhaustion.
|
||||
|
||||
## Use `onOneServer()` on Multi-Server Deployments
|
||||
|
||||
Without it, every server runs the same task simultaneously. Requires a shared cache driver (Redis, database, Memcached).
|
||||
|
||||
## Use `runInBackground()` for Concurrent Long Tasks
|
||||
|
||||
By default, tasks at the same tick run sequentially. A slow first task delays all subsequent ones. `runInBackground()` runs them as separate processes.
|
||||
|
||||
## Use `environments()` to Restrict Tasks
|
||||
|
||||
Prevent accidental execution of production-only tasks (billing, reporting) on staging.
|
||||
|
||||
```php
|
||||
Schedule::command('billing:charge')->monthly()->environments(['production']);
|
||||
```
|
||||
|
||||
## Use `takeUntilTimeout()` for Time-Bounded Processing
|
||||
|
||||
A task running every 15 minutes that processes an unbounded cursor can overlap with the next run. Bound execution time.
|
||||
|
||||
## Use Schedule Groups for Shared Configuration
|
||||
|
||||
Avoid repeating `->onOneServer()->timezone('America/New_York')` across many tasks.
|
||||
|
||||
```php
|
||||
Schedule::daily()
|
||||
->onOneServer()
|
||||
->timezone('America/New_York')
|
||||
->group(function () {
|
||||
Schedule::command('emails:send --force');
|
||||
Schedule::command('emails:prune');
|
||||
});
|
||||
```
|
||||
|
|
@ -1,198 +0,0 @@
|
|||
# Security Best Practices
|
||||
|
||||
## Mass Assignment Protection
|
||||
|
||||
Every model must define `$fillable` (whitelist) or `$guarded` (blacklist).
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
class User extends Model
|
||||
{
|
||||
protected $guarded = []; // All fields are mass assignable
|
||||
}
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
class User extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'name',
|
||||
'email',
|
||||
'password',
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
Never use `$guarded = []` on models that accept user input.
|
||||
|
||||
## Authorize Every Action
|
||||
|
||||
Use policies or gates in controllers. Never skip authorization.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
public function update(UpdatePostRequest $request, Post $post)
|
||||
{
|
||||
$post->update($request->validated());
|
||||
}
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
public function update(UpdatePostRequest $request, Post $post)
|
||||
{
|
||||
Gate::authorize('update', $post);
|
||||
|
||||
$post->update($request->validated());
|
||||
}
|
||||
```
|
||||
|
||||
Or via Form Request:
|
||||
|
||||
```php
|
||||
public function authorize(): bool
|
||||
{
|
||||
return $this->user()->can('update', $this->route('post'));
|
||||
}
|
||||
```
|
||||
|
||||
## Prevent SQL Injection
|
||||
|
||||
Always use parameter binding. Never interpolate user input into queries.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
DB::select("SELECT * FROM users WHERE name = '{$request->name}'");
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
User::where('name', $request->name)->get();
|
||||
|
||||
// Raw expressions with bindings
|
||||
User::whereRaw('LOWER(name) = ?', [strtolower($request->name)])->get();
|
||||
```
|
||||
|
||||
## Escape Output to Prevent XSS
|
||||
|
||||
Use `{{ }}` for HTML escaping. Only use `{!! !!}` for trusted, pre-sanitized content.
|
||||
|
||||
Incorrect:
|
||||
```blade
|
||||
{!! $user->bio !!}
|
||||
```
|
||||
|
||||
Correct:
|
||||
```blade
|
||||
{{ $user->bio }}
|
||||
```
|
||||
|
||||
## CSRF Protection
|
||||
|
||||
Include `@csrf` in all POST/PUT/DELETE Blade forms. In Inertia apps, the `@csrf` directive is automatically applied.
|
||||
|
||||
Incorrect:
|
||||
```blade
|
||||
<form method="POST" action="/posts">
|
||||
<input type="text" name="title">
|
||||
</form>
|
||||
```
|
||||
|
||||
Correct:
|
||||
```blade
|
||||
<form method="POST" action="/posts">
|
||||
@csrf
|
||||
<input type="text" name="title">
|
||||
</form>
|
||||
```
|
||||
|
||||
## Rate Limit Auth and API Routes
|
||||
|
||||
Apply `throttle` middleware to authentication and API routes.
|
||||
|
||||
```php
|
||||
RateLimiter::for('login', function (Request $request) {
|
||||
return Limit::perMinute(5)->by($request->ip());
|
||||
});
|
||||
|
||||
Route::post('/login', LoginController::class)->middleware('throttle:login');
|
||||
```
|
||||
|
||||
## Validate File Uploads
|
||||
|
||||
Validate extension, MIME type, and size. The `mimes` rule checks extensions; use `mimetypes` for actual MIME type validation. Never trust client-provided filenames.
|
||||
|
||||
```php
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'avatar' => ['required', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048'],
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
Store with generated filenames:
|
||||
|
||||
```php
|
||||
$path = $request->file('avatar')->store('avatars', 'public');
|
||||
```
|
||||
|
||||
## Keep Secrets Out of Code
|
||||
|
||||
Never commit `.env`. Access secrets via `config()` only.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
$key = env('API_KEY');
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
// config/services.php
|
||||
'api_key' => env('API_KEY'),
|
||||
|
||||
// In application code
|
||||
$key = config('services.api_key');
|
||||
```
|
||||
|
||||
## Audit Dependencies
|
||||
|
||||
Run `composer audit` periodically to check for known vulnerabilities in dependencies. Automate this in CI to catch issues before deployment.
|
||||
|
||||
```bash
|
||||
composer audit
|
||||
```
|
||||
|
||||
## Encrypt Sensitive Database Fields
|
||||
|
||||
Use `encrypted` cast for API keys/tokens and mark the attribute as `hidden`.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
class Integration extends Model
|
||||
{
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'api_key' => 'string',
|
||||
];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
class Integration extends Model
|
||||
{
|
||||
protected $hidden = ['api_key', 'api_secret'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'api_key' => 'encrypted',
|
||||
'api_secret' => 'encrypted',
|
||||
];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
|
@ -1,125 +0,0 @@
|
|||
# Conventions & Style
|
||||
|
||||
## Follow Laravel Naming Conventions
|
||||
|
||||
| What | Convention | Good | Bad |
|
||||
|------|-----------|------|-----|
|
||||
| Controller | singular | `ArticleController` | `ArticlesController` |
|
||||
| Model | singular | `User` | `Users` |
|
||||
| Table | plural, snake_case | `article_comments` | `articleComments` |
|
||||
| Pivot table | singular alphabetical | `article_user` | `user_article` |
|
||||
| Column | snake_case, no model name | `meta_title` | `article_meta_title` |
|
||||
| Foreign key | singular model + `_id` | `article_id` | `articles_id` |
|
||||
| Route | plural | `articles/1` | `article/1` |
|
||||
| Route name | snake_case with dots | `users.show_active` | `users.show-active` |
|
||||
| Method | camelCase | `getAll` | `get_all` |
|
||||
| Variable | camelCase | `$articlesWithAuthor` | `$articles_with_author` |
|
||||
| Collection | descriptive, plural | `$activeUsers` | `$data` |
|
||||
| Object | descriptive, singular | `$activeUser` | `$users` |
|
||||
| View | kebab-case | `show-filtered.blade.php` | `showFiltered.blade.php` |
|
||||
| Config | snake_case | `google_calendar.php` | `googleCalendar.php` |
|
||||
| Enum | singular | `UserType` | `UserTypes` |
|
||||
|
||||
## Prefer Shorter Readable Syntax
|
||||
|
||||
| Verbose | Shorter |
|
||||
|---------|---------|
|
||||
| `Session::get('cart')` | `session('cart')` |
|
||||
| `$request->session()->get('cart')` | `session('cart')` |
|
||||
| `$request->input('name')` | `$request->name` |
|
||||
| `return Redirect::back()` | `return back()` |
|
||||
| `Carbon::now()` | `now()` |
|
||||
| `App::make('Class')` | `app('Class')` |
|
||||
| `->where('column', '=', 1)` | `->where('column', 1)` |
|
||||
| `->orderBy('created_at', 'desc')` | `->latest()` |
|
||||
| `->orderBy('created_at', 'asc')` | `->oldest()` |
|
||||
| `->first()->name` | `->value('name')` |
|
||||
|
||||
## Use Laravel String & Array Helpers
|
||||
|
||||
Laravel provides `Str`, `Arr`, `Number`, and `Uri` helper classes that are more readable, chainable, and UTF-8 safe than raw PHP functions. Always prefer them.
|
||||
|
||||
Strings — use `Str` and fluent `Str::of()` over raw PHP:
|
||||
```php
|
||||
// Incorrect
|
||||
$slug = strtolower(str_replace(' ', '-', $title));
|
||||
$short = substr($text, 0, 100) . '...';
|
||||
$class = substr(strrchr('App\Models\User', '\\'), 1);
|
||||
|
||||
// Correct
|
||||
$slug = Str::slug($title);
|
||||
$short = Str::limit($text, 100);
|
||||
$class = class_basename('App\Models\User');
|
||||
```
|
||||
|
||||
Fluent strings — chain operations for complex transformations:
|
||||
```php
|
||||
// Incorrect
|
||||
$result = strtolower(trim(str_replace('_', '-', $input)));
|
||||
|
||||
// Correct
|
||||
$result = Str::of($input)->trim()->replace('_', '-')->lower();
|
||||
```
|
||||
|
||||
Key `Str` methods to prefer: `Str::slug()`, `Str::limit()`, `Str::contains()`, `Str::before()`, `Str::after()`, `Str::between()`, `Str::camel()`, `Str::snake()`, `Str::kebab()`, `Str::headline()`, `Str::squish()`, `Str::mask()`, `Str::uuid()`, `Str::ulid()`, `Str::random()`, `Str::is()`.
|
||||
|
||||
Arrays — use `Arr` over raw PHP:
|
||||
```php
|
||||
// Incorrect
|
||||
$name = isset($array['user']['name']) ? $array['user']['name'] : 'default';
|
||||
|
||||
// Correct
|
||||
$name = Arr::get($array, 'user.name', 'default');
|
||||
```
|
||||
|
||||
Key `Arr` methods: `Arr::get()`, `Arr::has()`, `Arr::only()`, `Arr::except()`, `Arr::first()`, `Arr::flatten()`, `Arr::pluck()`, `Arr::where()`, `Arr::wrap()`.
|
||||
|
||||
Numbers — use `Number` for display formatting:
|
||||
```php
|
||||
Number::format(1000000); // "1,000,000"
|
||||
Number::currency(1500, 'USD'); // "$1,500.00"
|
||||
Number::abbreviate(1000000); // "1M"
|
||||
Number::fileSize(1024 * 1024); // "1 MB"
|
||||
Number::percentage(75.5); // "75.5%"
|
||||
```
|
||||
|
||||
URIs — use `Uri` for URL manipulation:
|
||||
```php
|
||||
$uri = Uri::of('https://example.com/search')
|
||||
->withQuery(['q' => 'laravel', 'page' => 1]);
|
||||
```
|
||||
|
||||
Use `$request->string('name')` to get a fluent `Stringable` directly from request input for immediate chaining.
|
||||
|
||||
Use `search-docs` for the full list of available methods — these helpers are extensive.
|
||||
|
||||
## No Inline JS/CSS in Blade
|
||||
|
||||
Do not put JS or CSS in Blade templates. Do not put HTML in PHP classes.
|
||||
|
||||
Incorrect:
|
||||
```blade
|
||||
let article = `{{ json_encode($article) }}`;
|
||||
```
|
||||
|
||||
Correct:
|
||||
```blade
|
||||
<button class="js-fav-article" data-article='@json($article)'>{{ $article->name }}</button>
|
||||
```
|
||||
|
||||
Pass data to JS via data attributes or use a dedicated PHP-to-JS package.
|
||||
|
||||
## No Unnecessary Comments
|
||||
|
||||
Code should be readable on its own. Use descriptive method and variable names instead of comments. The only exception is config files, where descriptive comments are expected.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
// Check if there are any joins
|
||||
if (count((array) $builder->getQuery()->joins) > 0)
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
if ($this->hasJoins())
|
||||
```
|
||||
|
|
@ -1,43 +0,0 @@
|
|||
# Testing Best Practices
|
||||
|
||||
## Use `LazilyRefreshDatabase` Over `RefreshDatabase`
|
||||
|
||||
`RefreshDatabase` migrates once per process and wraps each test in a rolled-back transaction. `LazilyRefreshDatabase` skips even that first migration if the schema is already up to date.
|
||||
|
||||
## Use Model Assertions Over Raw Database Assertions
|
||||
|
||||
Incorrect: `$this->assertDatabaseHas('users', ['id' => $user->id]);`
|
||||
|
||||
Correct: `$this->assertModelExists($user);`
|
||||
|
||||
More expressive, type-safe, and fails with clearer messages.
|
||||
|
||||
## Use Factory States and Sequences
|
||||
|
||||
Named states make tests self-documenting. Sequences eliminate repetitive setup.
|
||||
|
||||
Incorrect: `User::factory()->create(['email_verified_at' => null]);`
|
||||
|
||||
Correct: `User::factory()->unverified()->create();`
|
||||
|
||||
## Use `Exceptions::fake()` to Assert Exception Reporting
|
||||
|
||||
Instead of `withoutExceptionHandling()`, use `Exceptions::fake()` to assert the correct exception was reported while the request completes normally.
|
||||
|
||||
## Call `Event::fake()` After Factory Setup
|
||||
|
||||
Model factories rely on model events (e.g., `creating` to generate UUIDs). Calling `Event::fake()` before factory calls silences those events, producing broken models.
|
||||
|
||||
Incorrect: `Event::fake(); $user = User::factory()->create();`
|
||||
|
||||
Correct: `$user = User::factory()->create(); Event::fake();`
|
||||
|
||||
## Use `recycle()` to Share Relationship Instances Across Factories
|
||||
|
||||
Without `recycle()`, nested factories create separate instances of the same conceptual entity.
|
||||
|
||||
```php
|
||||
Ticket::factory()
|
||||
->recycle(Airline::factory()->create())
|
||||
->create();
|
||||
```
|
||||
|
|
@ -1,75 +0,0 @@
|
|||
# Validation & Forms Best Practices
|
||||
|
||||
## Use Form Request Classes
|
||||
|
||||
Extract validation from controllers into dedicated Form Request classes.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
public function store(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'title' => 'required|max:255',
|
||||
'body' => 'required',
|
||||
]);
|
||||
}
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
public function store(StorePostRequest $request)
|
||||
{
|
||||
Post::create($request->validated());
|
||||
}
|
||||
```
|
||||
|
||||
## Array vs. String Notation for Rules
|
||||
|
||||
Array syntax is more readable and composes cleanly with `Rule::` objects. Prefer it in new code, but check existing Form Requests first and match whatever notation the project already uses.
|
||||
|
||||
```php
|
||||
// Preferred for new code
|
||||
'email' => ['required', 'email', Rule::unique('users')],
|
||||
|
||||
// Follow existing convention if the project uses string notation
|
||||
'email' => 'required|email|unique:users',
|
||||
```
|
||||
|
||||
## Always Use `validated()`
|
||||
|
||||
Get only validated data. Never use `$request->all()` for mass operations.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
Post::create($request->all());
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
Post::create($request->validated());
|
||||
```
|
||||
|
||||
## Use `Rule::when()` for Conditional Validation
|
||||
|
||||
```php
|
||||
'company_name' => [
|
||||
Rule::when($this->account_type === 'business', ['required', 'string', 'max:255']),
|
||||
],
|
||||
```
|
||||
|
||||
## Use the `after()` Method for Custom Validation
|
||||
|
||||
Use `after()` instead of `withValidator()` for custom validation logic that depends on multiple fields.
|
||||
|
||||
```php
|
||||
public function after(): array
|
||||
{
|
||||
return [
|
||||
function (Validator $validator) {
|
||||
if ($this->quantity > Product::find($this->product_id)?->stock) {
|
||||
$validator->errors()->add('quantity', 'Not enough stock.');
|
||||
}
|
||||
},
|
||||
];
|
||||
}
|
||||
```
|
||||
|
|
@ -1,112 +0,0 @@
|
|||
---
|
||||
name: mcp-development
|
||||
description: "Use this skill for Laravel MCP development. Trigger when creating or editing MCP tools, resources, prompts, servers, or UI apps in Laravel projects. Covers: artisan make:mcp-* generators, routes/ai.php, Tool/Resource/Prompt/AppResource classes, schema validation, shouldRegister(), OAuth setup, URI templates, read-only attributes, MCP debugging, MCP UI apps, the x-mcp::app Blade component, createMcpApp(), default AppResource handle() auto-infers view from class name, Response::view(), AppMeta/Csp/Permissions/appMeta() configuration, #[RendersApp] attribute, Library enum for CDN libraries (Tailwind, Alpine), and host theming via CSS variables. Use this whenever the user mentions MCP apps, MCP UI, interactive MCP resources, styling MCP apps with Tailwind or Alpine, or building visual interfaces for AI agents."
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
|
||||
# MCP Development
|
||||
|
||||
## Documentation
|
||||
|
||||
Use `search-docs` for detailed Laravel MCP patterns and documentation.
|
||||
|
||||
For MCP UI apps (interactive HTML resources), read `references/app.md` — it covers the full architecture, host theming CSS variables, tool-to-UI linking patterns, library scripts (Tailwind, Alpine via `Library`), and real-world examples.
|
||||
|
||||
## Basic Usage
|
||||
|
||||
Register MCP servers in `routes/ai.php`:
|
||||
|
||||
<!-- Register MCP Server -->
|
||||
```php
|
||||
use Laravel\Mcp\Facades\Mcp;
|
||||
|
||||
Mcp::web();
|
||||
```
|
||||
|
||||
### Creating MCP Primitives
|
||||
|
||||
```bash
|
||||
php artisan make:mcp-tool ToolName # Create a tool
|
||||
|
||||
php artisan make:mcp-resource ResourceName # Create a resource
|
||||
|
||||
php artisan make:mcp-prompt PromptName # Create a prompt
|
||||
|
||||
php artisan make:mcp-server ServerName # Create a server
|
||||
|
||||
php artisan make:mcp-app-resource DashboardApp # Create a UI app (2 files)
|
||||
|
||||
```
|
||||
|
||||
After creating primitives, register them in your server's `$tools`, `$resources`, or `$prompts` properties.
|
||||
|
||||
### Tools
|
||||
|
||||
<!-- MCP Tool Example -->
|
||||
```php
|
||||
use Illuminate\Json\Schema\JsonSchema;
|
||||
use Laravel\Mcp\Request;
|
||||
use Laravel\Mcp\Response;
|
||||
use Laravel\Mcp\Server\Tool;
|
||||
|
||||
class MyTool extends Tool
|
||||
{
|
||||
protected string $description = 'Describe what this tool does';
|
||||
|
||||
public function schema(JsonSchema $schema): array
|
||||
{
|
||||
return [
|
||||
'name' => $schema->string()->description('The name parameter')->required(),
|
||||
];
|
||||
}
|
||||
|
||||
public function handle(Request $request): Response
|
||||
{
|
||||
$request->validate(['name' => 'required|string']);
|
||||
|
||||
return Response::text('Hello, '.$request->get('name'));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Registering Primitives in a Server
|
||||
|
||||
<!-- Register Primitives in MCP Server -->
|
||||
```php
|
||||
use Laravel\Mcp\Server;
|
||||
|
||||
class AppServer extends Server
|
||||
{
|
||||
protected array $tools = [
|
||||
\App\Mcp\Tools\MyTool::class,
|
||||
];
|
||||
|
||||
protected array $resources = [
|
||||
\App\Mcp\Resources\MyResource::class,
|
||||
];
|
||||
|
||||
protected array $prompts = [
|
||||
\App\Mcp\Prompts\MyPrompt::class,
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
## MCP UI Apps
|
||||
|
||||
For MCP UI apps, read `references/app.md` — it covers quick start examples, full architecture, AppMeta/Csp/Permissions, `#[RendersApp]` tool linking, library scripts (Tailwind/Alpine via `Library`), host theming CSS variables, and real-world patterns.
|
||||
|
||||
## Verification
|
||||
|
||||
1. Check `routes/ai.php` for proper registration
|
||||
2. Test tool via MCP client
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
- Running `mcp:start` command (it hangs waiting for input)
|
||||
- Using HTTPS locally with Node-based MCP clients
|
||||
- Not using `search-docs` for the latest MCP documentation
|
||||
- Not registering MCP server routes in `routes/ai.php`
|
||||
- Do not register `ai.php` in `bootstrap.php`; it is registered automatically
|
||||
- OAuth registration supports custom URI schemes (e.g., `cursor://`, `vscode://`) for native desktop clients via `mcp.custom_schemes` config
|
||||
|
|
@ -1,940 +0,0 @@
|
|||
# MCP UI Apps Reference
|
||||
|
||||
## Quick Start
|
||||
|
||||
`make:mcp-app-resource DashboardApp` generates two files — a PHP registration stub and a Blade view. The entire app lives in the Blade view.
|
||||
|
||||
**PHP class** — renders the Blade view. The view name is auto-inferred from the class name (`mcp.<kebab-class-name>`), so the generated stub needs no changes unless you're passing additional server-side data:
|
||||
|
||||
```php
|
||||
class DashboardApp extends AppResource
|
||||
{
|
||||
public function handle(Request $request): Response
|
||||
{
|
||||
return Response::view('mcp.dashboard-app', [
|
||||
'title' => $this->title(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Blade view** — HTML structure + inline JS, everything in one file:
|
||||
|
||||
```blade
|
||||
<x-mcp::app title="Dashboard App">
|
||||
<x-slot:head>
|
||||
<script type="module">
|
||||
createMcpApp(async (app) => {
|
||||
document.getElementById('run-btn').addEventListener('click', async () => {
|
||||
const result = await app.callServerTool({ name: 'tool-name', arguments: {} });
|
||||
document.getElementById('output').textContent = result.content[0]?.text ?? '';
|
||||
});
|
||||
});
|
||||
</script>
|
||||
</x-slot:head>
|
||||
|
||||
<div id="app">
|
||||
<h1>Dashboard App</h1>
|
||||
<button id="run-btn">Run</button>
|
||||
<p id="output"></p>
|
||||
</div>
|
||||
</x-mcp::app>
|
||||
```
|
||||
|
||||
`createMcpApp` is a global pre-bundled by the package — no npm install, no imports, no Vite required. It handles connection, error handling, and host theming automatically.
|
||||
|
||||
---
|
||||
|
||||
## Core Concept: Tool + Resource
|
||||
|
||||
Every MCP App is built from two parts linked together:
|
||||
|
||||
- **Tool** — called by the LLM or host. Returns a text/data response and tells the host which UI resource to render via `_meta.ui.resourceUri`.
|
||||
- **AppResource** — serves the self-contained HTML app. The host fetches it after the tool is called and renders it in a sandboxed iframe.
|
||||
|
||||
```
|
||||
LLM calls Tool
|
||||
└─► Tool response includes _meta.ui.resourceUri → "ui://dashboard-app"
|
||||
└─► Host fetches AppResource at that URI
|
||||
└─► Host renders HTML in sandboxed iframe
|
||||
└─► createMcpApp() connects the iframe back to the server
|
||||
└─► UI calls app-only tools to load/refresh data
|
||||
```
|
||||
|
||||
The link is declared once with `#[RendersApp]` on the tool:
|
||||
|
||||
```php
|
||||
#[RendersApp(resource: DashboardApp::class)]
|
||||
class ShowDashboard extends Tool
|
||||
{
|
||||
public function handle(Request $request): Response
|
||||
{
|
||||
return Response::text('Dashboard loaded.');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
After that, the host handles fetching and rendering the resource automatically — you never reference the URI by hand.
|
||||
|
||||
---
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
MCP Apps add interactive UI to the Model Context Protocol. The server returns self-contained HTML with all JS/CSS inlined. The host renders it in a sandboxed iframe. Apps communicate back via `createMcpApp()` — a pre-bundled global implementing the MCP UI PostMessage protocol.
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────┐
|
||||
│ Host (Claude, ChatGPT, VS Code) │
|
||||
│ ┌───────────────────────────────────────┐ │
|
||||
│ │ Sandboxed iframe │ │
|
||||
│ │ ┌─────────────────────────────────┐ │ │
|
||||
│ │ │ Your MCP App (HTML/JS/CSS) │ │ │
|
||||
│ │ │ - Rendered by AppResource │ │ │
|
||||
│ │ │ - Single self-contained HTML │ │ │
|
||||
│ │ │ - Themed via host CSS vars │ │ │
|
||||
│ │ └─────────────────────────────────┘ │ │
|
||||
│ └───────────────────────────────────────┘ │
|
||||
└──────────────────┬──────────────────────────┘
|
||||
│ MCP Protocol (JSON-RPC)
|
||||
┌──────────────────▼──────────────────────────┐
|
||||
│ Laravel MCP Server │
|
||||
│ - AppResource → self-contained HTML │
|
||||
│ - Tool #[RendersApp] → triggers UI display │
|
||||
│ - resources/read → serves HTML + _meta.ui │
|
||||
└─────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
The server automatically advertises `io.modelcontextprotocol/ui` capability when any `AppResource` is registered. The client declares support in `capabilities.extensions["io.modelcontextprotocol/ui"]` during the initialize handshake.
|
||||
|
||||
---
|
||||
|
||||
## Server-Side
|
||||
|
||||
Minimal case — `handle()` renders the Blade view, entire app lives there:
|
||||
|
||||
```php
|
||||
class DashboardApp extends AppResource
|
||||
{
|
||||
public function handle(Request $request): Response
|
||||
{
|
||||
return Response::view('mcp.dashboard-app', [
|
||||
'title' => $this->title(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Auto-renders `resources/views/mcp/dashboard-app.blade.php` with `$title` available via `$this->title()`.
|
||||
|
||||
Override `handle()` only when passing additional server-side data:
|
||||
|
||||
```php
|
||||
class AnalyticsDashboard extends AppResource
|
||||
{
|
||||
public function handle(Request $request): Response
|
||||
{
|
||||
return Response::view('mcp.analytics-dashboard', [
|
||||
'title' => $this->title(),
|
||||
'metrics' => Metric::latest()->take(10)->get(),
|
||||
'totalUsers' => User::count(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`Response::view($view, $data = [], $mergeData = [])` renders a Blade view and returns it as text.
|
||||
|
||||
`Response::html($path)` reads an HTML file from disk and returns its content. Relative paths resolve via `resource_path()`:
|
||||
|
||||
```php
|
||||
class StaticApp extends AppResource
|
||||
{
|
||||
public function handle(Request $request): Response
|
||||
{
|
||||
return Response::html('mcp/static-app.html');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### AppMeta Configuration
|
||||
|
||||
The simplest way to configure UI metadata is via the `#[AppMeta]` attribute directly on your resource class:
|
||||
|
||||
```php
|
||||
use Laravel\Mcp\Server\Attributes\AppMeta;
|
||||
use Laravel\Mcp\Server\Ui\Enums\Library;
|
||||
use Laravel\Mcp\Server\Ui\Enums\Permission;
|
||||
|
||||
#[AppMeta(
|
||||
connectDomains: ['https://api.stripe.com'],
|
||||
permissions: [Permission::Camera, Permission::ClipboardWrite],
|
||||
prefersBorder: true,
|
||||
libraries: [Library::Tailwind, Library::Alpine],
|
||||
)]
|
||||
class PaymentsResource extends AppResource
|
||||
{
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
For dynamic or computed configuration, override `appMeta()` instead:
|
||||
|
||||
```php
|
||||
use Laravel\Mcp\Server\Ui\AppMeta;
|
||||
|
||||
public function appMeta(): AppMeta
|
||||
{
|
||||
return AppMeta::make()
|
||||
->csp(Csp::make()->connectDomains(config('services.api.domains')))
|
||||
->permissions(Permissions::make()->allow(Permission::Camera))
|
||||
->libraries(Library::Tailwind)
|
||||
->domain('sandbox.example.com');
|
||||
}
|
||||
```
|
||||
|
||||
#### Permission Enum
|
||||
|
||||
Use the `Permission` enum for type-safe permission configuration:
|
||||
|
||||
```php
|
||||
use Laravel\Mcp\Server\Ui\Enums\Permission;
|
||||
|
||||
Permission::Camera // 'camera'
|
||||
Permission::Microphone // 'microphone'
|
||||
Permission::Geolocation // 'geolocation'
|
||||
Permission::ClipboardWrite // 'clipboardWrite'
|
||||
```
|
||||
|
||||
#### Csp
|
||||
|
||||
Controls what external domains the iframe can access:
|
||||
|
||||
```php
|
||||
Csp::make()
|
||||
->connectDomains(['https://api.example.com']) // fetch, XHR, WebSocket origins
|
||||
->resourceDomains(['https://cdn.example.com']) // images, scripts, fonts, media
|
||||
->frameDomains(['https://embed.example.com']) // nested iframe origins
|
||||
->baseUriDomains(['https://base.example.com']); // base URI origins
|
||||
```
|
||||
|
||||
#### Permissions
|
||||
|
||||
```php
|
||||
Permissions::make()->allow(Permission::Camera, Permission::ClipboardWrite);
|
||||
|
||||
Permissions::make()
|
||||
->camera()
|
||||
->microphone()
|
||||
->geolocation()
|
||||
->clipboardWrite();
|
||||
```
|
||||
|
||||
Each enabled permission serializes as `"camera": {}` per the MCP spec.
|
||||
|
||||
#### AppMeta
|
||||
|
||||
```php
|
||||
AppMeta::make()
|
||||
->csp(Csp::make()->connectDomains([...]))
|
||||
->permissions(Permissions::make()->allow(Permission::Camera))
|
||||
->libraries(Library::Tailwind, Library::Alpine)
|
||||
->domain('sandbox.example.com') // dedicated sandbox origin (OAuth/CORS)
|
||||
->prefersBorder(false);
|
||||
```
|
||||
|
||||
`prefersBorder` defaults to `true`. `toArray()` omits null fields and empty nested objects. Library CDN domains are automatically merged into `csp.resourceDomains`.
|
||||
|
||||
#### domain
|
||||
|
||||
The `domain` field provides a stable origin that external APIs can allowlist for CORS. It is automatically resolved from `config('app.url')` (your `APP_URL` env variable) via `resolvedAppMeta()`, so most apps need no configuration. Override only when a resource needs a different origin:
|
||||
|
||||
```php
|
||||
#[AppMeta(domain: 'custom.example.com')]
|
||||
class PaymentsResource extends AppResource
|
||||
{
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
#### Library Scripts
|
||||
|
||||
The `libraries` parameter adds pre-configured CDN scripts to the `<head>` of your app. Available libraries:
|
||||
|
||||
```php
|
||||
use Laravel\Mcp\Server\Ui\Enums\Library;
|
||||
|
||||
Library::Tailwind // Tailwind CSS CDN + dark mode config
|
||||
Library::Alpine // Alpine.js CDN + x-cloak style
|
||||
```
|
||||
|
||||
When libraries are specified, the package automatically:
|
||||
|
||||
1. Injects the CDN `<script>` tags into the Blade view's `<head>` (after the MCP SDK, before your `<x-slot:head>`)
|
||||
2. Merges each library's CDN domains into `csp.resourceDomains` so the host allows loading them
|
||||
|
||||
Via attribute:
|
||||
|
||||
```php
|
||||
#[AppMeta(libraries: [Library::Tailwind])]
|
||||
class StyledApp extends AppResource
|
||||
{
|
||||
// Tailwind is available in the Blade view — no extra setup
|
||||
}
|
||||
```
|
||||
|
||||
Via fluent builder:
|
||||
|
||||
```php
|
||||
public function appMeta(): AppMeta
|
||||
{
|
||||
return AppMeta::make()
|
||||
->libraries(Library::Tailwind, Library::Alpine);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## View Layer
|
||||
|
||||
### `<x-mcp::app>` Blade Component
|
||||
|
||||
Renders a complete self-contained HTML document with the MCP SDK inlined. `createMcpApp` is available globally.
|
||||
|
||||
```blade
|
||||
<x-mcp::app title="Dashboard App">
|
||||
<x-slot:head>
|
||||
<script type="module">
|
||||
createMcpApp(async (app) => {
|
||||
document.getElementById('run-btn').addEventListener('click', async () => {
|
||||
const result = await app.callServerTool({ name: 'tool-name', arguments: {} });
|
||||
document.getElementById('output').textContent = result.content[0]?.text ?? '';
|
||||
});
|
||||
});
|
||||
</script>
|
||||
</x-slot:head>
|
||||
|
||||
<div id="app">
|
||||
<button id="run-btn">Run</button>
|
||||
<p id="output"></p>
|
||||
</div>
|
||||
</x-mcp::app>
|
||||
```
|
||||
|
||||
**Props and slots:**
|
||||
|
||||
| Name | Type | Description |
|
||||
| ------------- | ------------- | ---------------------------------------------------- |
|
||||
| `title` | Prop | Sets `<title>`. Optional. |
|
||||
| `head` | Named slot | Injected into `<head>` after the inlined SDK script. |
|
||||
| Default slot | Slot | Body content. |
|
||||
| `$attributes` | Attribute bag | Forwarded to `<body>` (e.g. `class="dark"`). |
|
||||
|
||||
The SDK is loaded from the `mcp.sdk` singleton (registered by `McpServiceProvider`) and inlined directly in a `<script>` tag. Library scripts (Tailwind, Alpine) configured via `#[AppMeta]` are injected after the SDK and before the `head` slot.
|
||||
|
||||
Publish the component: `php artisan vendor:publish --tag=mcp-views`.
|
||||
|
||||
To pass server-side data to JS, embed it as `data-*` attributes:
|
||||
|
||||
```blade
|
||||
<div id="app" data-users="{{ $users->toJson() }}">
|
||||
...
|
||||
</div>
|
||||
```
|
||||
|
||||
```js
|
||||
const users = JSON.parse(document.getElementById("app").dataset.users);
|
||||
```
|
||||
|
||||
## Client-Side
|
||||
|
||||
This package provides a simple MCP client library to easily work with client interactions.
|
||||
|
||||
### createMcpApp
|
||||
|
||||
Pre-bundled and inlined automatically — no npm install or imports required.
|
||||
|
||||
```js
|
||||
createMcpApp(async (app) => {
|
||||
// app is ready — connection established, theming applied
|
||||
});
|
||||
```
|
||||
|
||||
### Tools
|
||||
|
||||
#### app.callServerTool()
|
||||
|
||||
Accepts an object or positional arguments:
|
||||
|
||||
```js
|
||||
// Object form
|
||||
const result = await app.callServerTool({ name: 'get-analytics', arguments: { dateRange: '7d' } });
|
||||
|
||||
// Positional form
|
||||
const result = await app.callServerTool('get-analytics', { dateRange: '7d' });
|
||||
|
||||
// result structure depends on the server's tool response
|
||||
const text = result.content[0]?.text ?? "";
|
||||
```
|
||||
|
||||
All tool results share a standard structure:
|
||||
|
||||
| Property | Type | Description |
|
||||
| --------- | --------- | ------------------------------------------------------------------------- |
|
||||
| `content` | `Array` | Content items returned by the tool (each has `type` and `text` or `data`) |
|
||||
| `isError` | `boolean` | `true` when the tool returned an error response |
|
||||
|
||||
Always check `result.isError` before consuming `content`. See [Error Handling](#error-handling) for a full example.
|
||||
|
||||
### Resources
|
||||
|
||||
#### app.listResources()
|
||||
|
||||
```js
|
||||
const resources = await app.listResources();
|
||||
// or with cursor for pagination
|
||||
const resources = await app.listResources("cursor-value");
|
||||
// or object form
|
||||
const resources = await app.listResources({ cursor: "cursor-value" });
|
||||
```
|
||||
|
||||
#### app.readResource()
|
||||
|
||||
```js
|
||||
const resource = await app.readResource("ui://my-resource");
|
||||
// or object form
|
||||
const resource = await app.readResource({ uri: "ui://my-resource" });
|
||||
```
|
||||
|
||||
### Messaging
|
||||
|
||||
#### app.sendMessage()
|
||||
|
||||
Send a message to the model (creates a conversation turn):
|
||||
|
||||
```js
|
||||
// Object form with structured content
|
||||
await app.sendMessage({
|
||||
role: "user",
|
||||
content: [{ type: "text", text: "User submitted the form." }],
|
||||
});
|
||||
|
||||
// Shorthand — plain string content with optional role (defaults to 'user')
|
||||
await app.sendMessage("User submitted the form.");
|
||||
await app.sendMessage("System event occurred.", "user");
|
||||
```
|
||||
|
||||
### Host Context
|
||||
|
||||
#### app.getHostContext()
|
||||
|
||||
Returns the current host context, including theme and style variables:
|
||||
|
||||
```js
|
||||
const ctx = app.getHostContext();
|
||||
ctx?.theme; // 'light' | 'dark'
|
||||
ctx?.styles?.variables; // CSS variable map from host
|
||||
ctx?.styles?.css?.fonts; // font CSS from host
|
||||
```
|
||||
|
||||
#### app.getHostInfo()
|
||||
|
||||
```js
|
||||
const info = app.getHostInfo();
|
||||
```
|
||||
|
||||
#### app.getHostCapabilities()
|
||||
|
||||
```js
|
||||
const caps = app.getHostCapabilities();
|
||||
```
|
||||
|
||||
### Navigation & Files
|
||||
|
||||
#### app.openLink()
|
||||
|
||||
```js
|
||||
await app.openLink("https://example.com");
|
||||
// or object form
|
||||
await app.openLink({ url: "https://example.com" });
|
||||
```
|
||||
|
||||
#### app.downloadFile()
|
||||
|
||||
```js
|
||||
await app.downloadFile("file contents here");
|
||||
// or object form
|
||||
await app.downloadFile({ contents: "file contents here" });
|
||||
```
|
||||
|
||||
### Display
|
||||
|
||||
#### app.requestDisplayMode()
|
||||
|
||||
```js
|
||||
await app.requestDisplayMode("fullscreen");
|
||||
// or object form
|
||||
await app.requestDisplayMode({ mode: "fullscreen" });
|
||||
```
|
||||
|
||||
#### app.resize() / app.autoResize()
|
||||
|
||||
`resize()` sends a one-time size notification. `autoResize()` uses `ResizeObserver` to continuously notify the host of size changes. It returns a cleanup function that disconnects the observer — useful if you need to stop observing before teardown. The observer is also automatically disconnected on teardown.
|
||||
|
||||
```js
|
||||
const stopObserving = app.autoResize();
|
||||
|
||||
// Later, if needed:
|
||||
stopObserving();
|
||||
```
|
||||
|
||||
### Model Context
|
||||
|
||||
#### app.updateModelContext()
|
||||
|
||||
```js
|
||||
await app.updateModelContext({ key: "value" });
|
||||
```
|
||||
|
||||
### Lifecycle
|
||||
|
||||
#### app.requestTeardown()
|
||||
|
||||
Sends a teardown notification to the host.
|
||||
|
||||
```js
|
||||
app.requestTeardown();
|
||||
```
|
||||
|
||||
### Logging
|
||||
|
||||
#### app.sendLog()
|
||||
|
||||
```js
|
||||
// Positional form
|
||||
await app.sendLog("info", "Processing started", "my-logger");
|
||||
|
||||
// Object form
|
||||
await app.sendLog({
|
||||
level: "info",
|
||||
data: "Processing started",
|
||||
logger: "my-logger",
|
||||
});
|
||||
```
|
||||
|
||||
### Event Handlers
|
||||
|
||||
Register callbacks for host-side events. Tool input/result/cancelled events are queued until a handler is registered, then flushed.
|
||||
|
||||
```js
|
||||
createMcpApp(async (app) => {
|
||||
app.onToolInput((params) => {
|
||||
/* tool input received */
|
||||
});
|
||||
app.onToolInputPartial((params) => {
|
||||
/* partial tool input */
|
||||
});
|
||||
app.onToolResult((params) => {
|
||||
/* tool result received */
|
||||
});
|
||||
app.onToolCancelled((params) => {
|
||||
/* tool was cancelled */
|
||||
});
|
||||
app.onHostContextChanged((ctx) => {
|
||||
/* theme/styles changed */
|
||||
});
|
||||
app.onTeardown(async () => {
|
||||
/* cleanup before teardown */
|
||||
});
|
||||
app.onCallTool(async (params) => {
|
||||
/* host requests tool call */
|
||||
});
|
||||
app.onListTools(async (params) => {
|
||||
/* host requests tool list */
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Host Theming
|
||||
|
||||
`createMcpApp` automatically applies host theming on connect and on context change:
|
||||
|
||||
- Sets `data-theme` attribute and `color-scheme` on `<html>`
|
||||
- Applies CSS variables from `hostContext.styles.variables` to `:root`
|
||||
- Injects font CSS from `hostContext.styles.css.fonts` into a `<style>` tag
|
||||
|
||||
The specific CSS variables available depend on the host. Always provide fallback values — use `light-dark()` for theme-aware defaults:
|
||||
|
||||
```css
|
||||
:root {
|
||||
--color-background-primary: light-dark(#ffffff, #171717);
|
||||
--color-text-primary: light-dark(#171717, #fafafa);
|
||||
--color-text-secondary: light-dark(#525252, #a3a3a3);
|
||||
--color-border-primary: light-dark(#e5e5e5, #404040);
|
||||
--font-sans: system-ui, -apple-system, sans-serif;
|
||||
--border-radius-md: 8px;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: var(--font-sans);
|
||||
background: var(--color-background-primary);
|
||||
color: var(--color-text-primary);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.card {
|
||||
background: var(--color-background-secondary);
|
||||
border: 1px solid var(--color-border-primary);
|
||||
border-radius: var(--border-radius-md);
|
||||
padding: 1rem;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Tool-to-UI Linking
|
||||
|
||||
### #[RendersApp] Attribute
|
||||
|
||||
Associates a Tool with a UI Resource. When the tool is called, the host fetches and renders the linked resource.
|
||||
|
||||
```php
|
||||
use Laravel\Mcp\Server\Attributes\RendersApp;
|
||||
use Laravel\Mcp\Server\Ui\Enums\Visibility;
|
||||
|
||||
// Both model and app can call this tool (default)
|
||||
#[RendersApp(resource: DashboardApp::class)]
|
||||
class ShowDashboard extends Tool { ... }
|
||||
|
||||
// Only the app can call this tool (private to the UI)
|
||||
#[RendersApp(resource: DashboardApp::class, visibility: [Visibility::App])]
|
||||
class RefreshDashboardData extends Tool { ... }
|
||||
```
|
||||
|
||||
**Visibility:**
|
||||
|
||||
The `Visibility` enum (`Laravel\Mcp\Server\Ui\Enums\Visibility`) has two cases: `Model` and `App`. The default is `[Visibility::Model, Visibility::App]`.
|
||||
|
||||
| Visibility | Model | App | Use case |
|
||||
| -------------------------------------- | ----- | --- | ------------------------------------------------------ |
|
||||
| `[Visibility::Model, Visibility::App]` | Yes | Yes | Primary tools that trigger UI display |
|
||||
| `[Visibility::App]` | No | Yes | Backend actions the UI calls (refresh, save, paginate) |
|
||||
| `[Visibility::Model]` | Yes | No | Model-only tools linked to a UI |
|
||||
|
||||
### Primary + Private Pattern
|
||||
|
||||
```php
|
||||
#[RendersApp(resource: DashboardApp::class)]
|
||||
class ShowDashboard extends Tool
|
||||
{
|
||||
public function handle(Request $request): Response
|
||||
{
|
||||
return Response::text('Dashboard loaded.');
|
||||
}
|
||||
}
|
||||
|
||||
#[RendersApp(resource: DashboardApp::class, visibility: [Visibility::App])]
|
||||
class GetDashboardMetrics extends Tool
|
||||
{
|
||||
public function handle(Request $request): Response
|
||||
{
|
||||
return Response::json(Metric::latest()->take(50)->get());
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Testing
|
||||
|
||||
```php
|
||||
it('returns html content', function () {
|
||||
MyServer::readResource(DashboardApp::class)
|
||||
->assertSee('<div id="app">');
|
||||
});
|
||||
|
||||
it('has correct mime type and uri scheme', function () {
|
||||
$resource = new DashboardApp;
|
||||
$data = $resource->toArray();
|
||||
|
||||
expect($data['mimeType'])->toBe('text/html;profile=mcp-app')
|
||||
->and($data['_meta']['ui'])->toBeArray()
|
||||
->and($resource->uri())->toStartWith('ui://');
|
||||
});
|
||||
|
||||
it('configures ui meta correctly', function () {
|
||||
$meta = (new DashboardApp)->resolvedAppMeta();
|
||||
|
||||
expect($meta['csp']['connectDomains'])->toContain('https://api.example.com')
|
||||
->and($meta['permissions'])->toHaveKey('clipboardWrite');
|
||||
});
|
||||
|
||||
it('includes ui metadata in tool listing', function () {
|
||||
MyServer::listTools()->assertSee('show-dashboard');
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Patterns
|
||||
|
||||
### Real-time Polling
|
||||
|
||||
Use app-only tools to fetch fresh data at regular intervals from the UI:
|
||||
|
||||
```php
|
||||
#[RendersApp(resource: MonitorApp::class, visibility: [Visibility::App])]
|
||||
class GetMonitorData extends Tool
|
||||
{
|
||||
protected string $description = 'Fetch latest monitor metrics';
|
||||
|
||||
public function handle(Request $request): Response
|
||||
{
|
||||
return Response::json([
|
||||
'cpu' => sys_getloadavg()[0],
|
||||
'memory' => memory_get_usage(true),
|
||||
'timestamp' => now()->toISOString(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
createMcpApp(async (app) => {
|
||||
async function poll() {
|
||||
const result = await app.callServerTool('get-monitor-data');
|
||||
const data = JSON.parse(result.content[0]?.text ?? '{}');
|
||||
document.getElementById('cpu').textContent = data.cpu;
|
||||
}
|
||||
|
||||
setInterval(poll, 2000);
|
||||
poll();
|
||||
});
|
||||
```
|
||||
|
||||
### Chunked Data Loading
|
||||
|
||||
For large datasets, implement pagination via app-only tools:
|
||||
|
||||
```php
|
||||
#[RendersApp(resource: LogViewerApp::class, visibility: [Visibility::App])]
|
||||
class GetLogChunk extends Tool
|
||||
{
|
||||
protected string $description = 'Fetch a chunk of log entries';
|
||||
|
||||
public function schema(JsonSchema $schema): array
|
||||
{
|
||||
return [
|
||||
'offset' => $schema->integer()->description('Byte offset to start from')->required(),
|
||||
'limit' => $schema->integer()->description('Max bytes to return'),
|
||||
];
|
||||
}
|
||||
|
||||
public function handle(Request $request): Response
|
||||
{
|
||||
$request->validate(['offset' => 'required|integer', 'limit' => 'integer']);
|
||||
|
||||
$offset = $request->get('offset');
|
||||
$limit = $request->get('limit', 500_000);
|
||||
$content = Storage::get('logs/app.log');
|
||||
$chunk = substr($content, $offset, $limit);
|
||||
|
||||
return Response::json([
|
||||
'data' => $chunk,
|
||||
'offset' => $offset,
|
||||
'totalBytes' => strlen($content),
|
||||
'hasMore' => ($offset + $limit) < strlen($content),
|
||||
]);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Binary Resource Serving
|
||||
|
||||
Deliver images and binary content through MCP resources using `Response::blob()`:
|
||||
|
||||
```php
|
||||
#[RendersApp(resource: GalleryApp::class, visibility: [Visibility::App])]
|
||||
class GetImage extends Tool
|
||||
{
|
||||
protected string $description = 'Fetch an image by ID';
|
||||
|
||||
public function handle(Request $request): Response
|
||||
{
|
||||
$request->validate(['id' => 'required|integer']);
|
||||
|
||||
$image = Image::findOrFail($request->get('id'));
|
||||
$data = base64_encode(Storage::get($image->path));
|
||||
|
||||
return Response::blob($data);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In the client, convert the base64 blob to a data URI for rendering:
|
||||
|
||||
```js
|
||||
const result = await app.callServerTool('get-image', { id: 42 });
|
||||
const blob = result.content[0];
|
||||
img.src = `data:${blob.mimeType};base64,${blob.data}`;
|
||||
```
|
||||
|
||||
### Streaming Argument Previews
|
||||
|
||||
Use `onToolInputPartial` to show previews as the model streams tool arguments:
|
||||
|
||||
```js
|
||||
createMcpApp(async (app) => {
|
||||
app.onToolInputPartial((params) => {
|
||||
try {
|
||||
const partial = JSON.parse(params.arguments);
|
||||
if (partial.query) {
|
||||
document.getElementById("preview").textContent = partial.query;
|
||||
}
|
||||
} catch {
|
||||
// partial JSON — ignore until parseable
|
||||
}
|
||||
});
|
||||
|
||||
app.onToolResult((params) => {
|
||||
const data = JSON.parse(params.result.content[0]?.text ?? "{}");
|
||||
renderResults(data);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### View State Persistence
|
||||
|
||||
Use `localStorage` to preserve UI state across re-renders. For important state, persist server-side via an app-only tool:
|
||||
|
||||
```js
|
||||
createMcpApp(async (app) => {
|
||||
const STATE_KEY = "dashboard-view-state";
|
||||
|
||||
// Restore from localStorage
|
||||
const saved = JSON.parse(localStorage.getItem(STATE_KEY) || "{}");
|
||||
if (saved.activeTab) selectTab(saved.activeTab);
|
||||
|
||||
// Save on interaction
|
||||
function saveState(state) {
|
||||
localStorage.setItem(STATE_KEY, JSON.stringify(state));
|
||||
}
|
||||
|
||||
// For durable state, persist server-side
|
||||
async function saveServerState(state) {
|
||||
await app.callServerTool('save-dashboard-state', { state: JSON.stringify(state) });
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### Fullscreen Toggling
|
||||
|
||||
Switch between inline and fullscreen display modes and react to mode changes:
|
||||
|
||||
```js
|
||||
createMcpApp(async (app) => {
|
||||
document.getElementById("expand-btn").addEventListener("click", () => {
|
||||
app.requestDisplayMode("fullscreen");
|
||||
});
|
||||
|
||||
app.onHostContextChanged((ctx) => {
|
||||
document.body.classList.toggle(
|
||||
"fullscreen",
|
||||
ctx.displayMode === "fullscreen",
|
||||
);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### Model Context Updates
|
||||
|
||||
Keep the model informed about what the user is viewing so it can provide relevant assistance:
|
||||
|
||||
```js
|
||||
createMcpApp(async (app) => {
|
||||
async function notifyContext(view, detail) {
|
||||
await app.updateModelContext({
|
||||
currentView: view,
|
||||
detail: detail,
|
||||
});
|
||||
}
|
||||
|
||||
// Notify on tab change
|
||||
document.querySelectorAll(".tab").forEach((tab) => {
|
||||
tab.addEventListener("click", () => {
|
||||
notifyContext(tab.dataset.view, { filters: getActiveFilters() });
|
||||
});
|
||||
});
|
||||
|
||||
// For large payloads, follow up with sendMessage
|
||||
await app.updateModelContext({ currentView: "report", rows: 5000 });
|
||||
await app.sendMessage("The user is viewing a report with 5000 rows.");
|
||||
});
|
||||
```
|
||||
|
||||
### Pause Offscreen Views
|
||||
|
||||
Conserve resources by pausing animations and polling when the view is not visible:
|
||||
|
||||
```js
|
||||
createMcpApp(async (app) => {
|
||||
let pollInterval = null;
|
||||
|
||||
function startPolling() {
|
||||
if (!pollInterval) {
|
||||
pollInterval = setInterval(fetchData, 2000);
|
||||
}
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
clearInterval(pollInterval);
|
||||
pollInterval = null;
|
||||
}
|
||||
|
||||
const observer = new IntersectionObserver(([entry]) => {
|
||||
entry.isIntersecting ? startPolling() : stopPolling();
|
||||
});
|
||||
|
||||
observer.observe(document.documentElement);
|
||||
startPolling();
|
||||
});
|
||||
```
|
||||
|
||||
### Error Handling
|
||||
|
||||
Return `Response::error()` from tools and use `updateModelContext()` to signal degraded state:
|
||||
|
||||
```php
|
||||
class ProcessData extends Tool
|
||||
{
|
||||
public function handle(Request $request): Response
|
||||
{
|
||||
$request->validate(['input' => 'required|string']);
|
||||
|
||||
if (strlen($request->get('input')) > 10_000) {
|
||||
return Response::error('Input exceeds 10KB limit.');
|
||||
}
|
||||
|
||||
return Response::json(process($request->get('input')));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
createMcpApp(async (app) => {
|
||||
const result = await app.callServerTool('process-data', { input: value });
|
||||
|
||||
if (result.isError) {
|
||||
document.getElementById("error").textContent =
|
||||
result.content[0]?.text ?? "Unknown error";
|
||||
await app.updateModelContext({
|
||||
state: "error",
|
||||
message: result.content[0]?.text,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
renderOutput(JSON.parse(result.content[0]?.text ?? "{}"));
|
||||
});
|
||||
```
|
||||
|
|
@ -1,205 +0,0 @@
|
|||
---
|
||||
name: passport-development
|
||||
description: "Develops OAuth2 API authentication with Laravel Passport. Activates when installing or configuring Passport; setting up OAuth2 grants (authorization code, client credentials, personal access tokens, device authorization); managing OAuth clients; protecting API routes with token authentication; defining or checking token scopes; configuring SPA cookie authentication; handling token lifetimes and refresh tokens; or when the user mentions Passport, OAuth2, API tokens, bearer tokens, or API authentication. Make sure to use this skill whenever the user works with OAuth2, API tokens, or third-party API access, even if they don't explicitly mention Passport."
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
|
||||
# Passport OAuth2 Authentication
|
||||
|
||||
## Documentation First
|
||||
|
||||
**Always use `search-docs` before writing Passport code.** The documentation covers every grant type, configuration option, and edge case in detail. This skill teaches you how to navigate Passport — the docs have the implementation specifics.
|
||||
|
||||
```
|
||||
search-docs(queries: ["Passport installation"], packages: ["laravel/framework@12.x"])
|
||||
```
|
||||
|
||||
The Passport docs live under the `laravel/framework` package — not `laravel/passport`.
|
||||
|
||||
## When to Apply
|
||||
|
||||
Activate this skill when:
|
||||
|
||||
- Installing or configuring Passport
|
||||
- Setting up OAuth2 authorization grants
|
||||
- Creating or managing OAuth clients
|
||||
- Protecting API routes with token authentication
|
||||
- Defining or checking token scopes
|
||||
- Configuring SPA cookie-based authentication
|
||||
- Choosing between Passport and Sanctum
|
||||
|
||||
## Passport vs. Sanctum
|
||||
|
||||
**Passport** is a full OAuth2 server — use it when third-party applications need to consume your API and when you need OAuth2 authorization code grants, client credentials for machine-to-machine auth, or device authorization flow.
|
||||
|
||||
**Sanctum** is simpler — use it when first-party SPAs, third parties, or mobile apps consume the API but you don't need the full OAuth2 grant flows.
|
||||
|
||||
## Installation
|
||||
|
||||
Three steps are always required:
|
||||
|
||||
### 1. Install Passport
|
||||
|
||||
```bash
|
||||
php artisan install:api --passport
|
||||
```
|
||||
|
||||
This publishes migrations, generates encryption keys, and registers routes.
|
||||
|
||||
### 2. Configure the User model
|
||||
|
||||
The User model needs both the `HasApiTokens` trait AND the `OAuthenticatable` interface. Missing the interface is the most common Passport setup mistake — it causes runtime errors that can be confusing to debug.
|
||||
|
||||
```php
|
||||
use Laravel\Passport\Contracts\OAuthenticatable;
|
||||
use Laravel\Passport\HasApiTokens;
|
||||
|
||||
class User extends Authenticatable implements OAuthenticatable
|
||||
{
|
||||
use HasApiTokens;
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Configure the auth guard
|
||||
|
||||
The `api` guard must use the `passport` driver in `config/auth.php`. Using `token` or `sanctum` here silently breaks Passport authentication.
|
||||
|
||||
```php
|
||||
'guards' => [
|
||||
'api' => [
|
||||
'driver' => 'passport',
|
||||
'provider' => 'users',
|
||||
],
|
||||
],
|
||||
```
|
||||
|
||||
## Choosing a Grant Type
|
||||
|
||||
Matching the right grant to the use case is the most important Passport decision. Use `search-docs` for implementation details of any grant.
|
||||
|
||||
| Use Case | Grant Type | Client Flag |
|
||||
|----------|-----------|-------------|
|
||||
| Third-party app accessing user data | Authorization Code | (default) |
|
||||
| Mobile/SPA without client secret | Authorization Code + PKCE | `--public` |
|
||||
| Machine-to-machine, no user context | Client Credentials | `--client` |
|
||||
| User-generated API keys | Personal Access Tokens | `--personal` |
|
||||
| Smart TV, CLI, IoT devices | Device Authorization | `--device` |
|
||||
|
||||
**Legacy grants** (Password, Implicit) are disabled by default and not recommended. They must be explicitly enabled with `Passport::enablePasswordGrant()` or `Passport::enableImplicitGrant()`.
|
||||
|
||||
## Client Management
|
||||
|
||||
Create clients with the appropriate flag for the grant type:
|
||||
|
||||
```bash
|
||||
php artisan passport:client # Authorization code
|
||||
|
||||
php artisan passport:client --public # PKCE (no secret)
|
||||
|
||||
php artisan passport:client --client # Client credentials
|
||||
|
||||
php artisan passport:client --personal # Personal access tokens
|
||||
|
||||
php artisan passport:client --device # Device authorization
|
||||
|
||||
```
|
||||
|
||||
Additional flags: `--name=`, `--redirect_uri=`, `--provider=`.
|
||||
|
||||
Client secrets are hashed by default — the plain-text secret is only shown at creation time and cannot be retrieved later.
|
||||
|
||||
## Protecting Routes
|
||||
|
||||
Apply `auth:api` middleware. Clients send tokens via the `Authorization: Bearer <token>` header.
|
||||
|
||||
```php
|
||||
Route::get('/user', function (Request $request) {
|
||||
return $request->user();
|
||||
})->middleware('auth:api');
|
||||
```
|
||||
|
||||
### Scope Enforcement
|
||||
|
||||
Scope middleware must come alongside `auth:api`:
|
||||
|
||||
- `CheckToken::using('scope1', 'scope2')` — requires ALL listed scopes
|
||||
- `CheckTokenForAnyScope::using('scope1', 'scope2')` — requires ANY listed scope
|
||||
- `EnsureClientIsResourceOwner::using('scope1')` — restricts to client credential tokens
|
||||
|
||||
```php
|
||||
use Laravel\Passport\Http\Middleware\CheckToken;
|
||||
|
||||
Route::get('/orders', function () {
|
||||
// ...
|
||||
})->middleware(['auth:api', CheckToken::using('orders:read')]);
|
||||
```
|
||||
|
||||
### Programmatic scope checking
|
||||
|
||||
```php
|
||||
if ($request->user()->tokenCan('place-orders')) {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
Use `search-docs` for full scope middleware registration and usage patterns.
|
||||
|
||||
## Key Configuration
|
||||
|
||||
Configure in `AppServiceProvider::boot()`. Use `search-docs` for the full list of options.
|
||||
|
||||
```php
|
||||
// Token lifetimes (each is independent)
|
||||
Passport::tokensExpireIn(now()->addDays(15));
|
||||
Passport::refreshTokensExpireIn(now()->addDays(30));
|
||||
Passport::personalAccessTokensExpireIn(now()->addMonths(6));
|
||||
|
||||
// Define scopes
|
||||
Passport::tokensCan([
|
||||
'place-orders' => 'Place orders',
|
||||
'check-status' => 'Check order status',
|
||||
]);
|
||||
```
|
||||
|
||||
## SPA Cookie Authentication
|
||||
|
||||
For first-party SPAs, the `CreateFreshApiToken` middleware issues a `laravel_token` cookie containing an encrypted JWT. The SPA must include CSRF tokens — missing the `X-CSRF-TOKEN` or `X-XSRF-TOKEN` header causes 419 errors.
|
||||
|
||||
Use `search-docs` for setup details — this feature has specific CSRF and cookie configuration requirements.
|
||||
|
||||
## Testing
|
||||
|
||||
Passport provides helpers to bypass full OAuth flows in tests:
|
||||
|
||||
```php
|
||||
Passport::actingAs($user, ['scope1', 'scope2']);
|
||||
Passport::actingAsClient($client, ['scope1']);
|
||||
```
|
||||
|
||||
## Token Maintenance
|
||||
|
||||
```bash
|
||||
php artisan passport:purge # Purge revoked & expired
|
||||
|
||||
php artisan passport:purge --revoked # Only revoked
|
||||
|
||||
php artisan passport:purge --expired # Only expired
|
||||
|
||||
```
|
||||
|
||||
Schedule `passport:purge` for regular expired token clean-up.
|
||||
|
||||
## Events
|
||||
|
||||
All in `Laravel\Passport\Events`: `AccessTokenCreated`, `AccessTokenRevoked`, `RefreshTokenCreated`.
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
- **Missing `OAuthenticatable` interface** — both the `HasApiTokens` trait and the `OAuthenticatable` interface are required on the User model. Missing the interface causes runtime errors.
|
||||
- **Wrong guard driver** — the `api` guard must use `passport`, not `token` or `sanctum`. This fails silently.
|
||||
- **Token lifetime confusion** — access token, refresh token, and personal access token lifetimes are all independent settings.
|
||||
- **Missing CSRF for SPA cookie auth** — `CreateFreshApiToken` requires CSRF tokens. Use `Passport::ignoreCsrfToken()` only if you understand the security implications.
|
||||
- **Client secrets are hashed** — the plain-text secret is only available at creation time.
|
||||
- **Legacy grants are disabled** — Password and Implicit grants must be explicitly enabled and are not recommended.
|
||||
|
|
@ -1,203 +0,0 @@
|
|||
---
|
||||
name: pest-testing
|
||||
description: "Use this skill for Pest PHP testing in Laravel projects only. Trigger whenever any test is being written, edited, fixed, or refactored — including fixing tests that broke after a code change, adding assertions, converting PHPUnit to Pest, adding datasets, and TDD workflows. Always activate when the user asks how to write something in Pest, mentions test files or directories (tests/Feature, tests/Unit, tests/Browser), or needs browser testing, smoke testing multiple pages for JS errors, architecture tests, or faster test runs with Test Impact Analysis. Covers: test()/it()/expect() syntax, datasets, mocking, browser testing (visit/click/fill), smoke testing, arch(), Livewire component tests, RefreshDatabase, Tia (--tia), sharding, and all Pest 5 features. Do not use for factories, seeders, migrations, controllers, models, or non-test PHP code."
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
|
||||
# Pest Testing 5
|
||||
|
||||
## Documentation
|
||||
|
||||
Use `search-docs` for detailed Pest 5 patterns and documentation.
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### Creating Tests
|
||||
|
||||
All tests must be written using Pest. Use `php artisan make:test --pest {name}`.
|
||||
|
||||
The `{name}` argument should include only the path and test name, but should not include the test suite.
|
||||
- Incorrect: `php artisan make:test --pest Feature/SomeFeatureTest` will generate `tests/Feature/Feature/SomeFeatureTest.php`
|
||||
- Correct: `php artisan make:test --pest SomeControllerTest` will generate `tests/Feature/SomeControllerTest.php`
|
||||
- Incorrect: `php artisan make:test --pest --unit Unit/SomeServiceTest` will generate `tests/Unit/Unit/SomeServiceTest.php`
|
||||
- Correct: `php artisan make:test --pest --unit SomeServiceTest` will generate `tests/Unit/SomeServiceTest.php`
|
||||
|
||||
### Test Organization
|
||||
|
||||
- Unit/Feature tests: `tests/Feature` and `tests/Unit` directories.
|
||||
- Browser tests: `tests/Browser/` directory.
|
||||
- Do NOT remove tests without approval - these are core application code.
|
||||
|
||||
### Basic Test Structure
|
||||
|
||||
Pest supports both `test()` and `it()` functions. Before writing new tests, check existing test files in the same directory to match the project's convention. Use `test()` if existing tests use `test()`, or `it()` if they use `it()`.
|
||||
|
||||
<!-- Basic Pest Test Example -->
|
||||
```php
|
||||
it('is true', function () {
|
||||
expect(true)->toBeTrue();
|
||||
});
|
||||
```
|
||||
|
||||
### Running Tests
|
||||
|
||||
- Run minimal tests with filter before finalizing: `php artisan test --compact --filter=testName`.
|
||||
- Run all tests: `php artisan test --compact`.
|
||||
- Run file: `php artisan test --compact tests/Feature/ExampleTest.php`.
|
||||
- Run only tests affected by recent changes (Tia): `./vendor/bin/pest --parallel --tia`.
|
||||
|
||||
## Assertions
|
||||
|
||||
Use specific assertions (`assertSuccessful()`, `assertNotFound()`) instead of `assertStatus()`:
|
||||
|
||||
<!-- Pest Response Assertion -->
|
||||
```php
|
||||
it('returns all', function () {
|
||||
$this->postJson('/api/docs', [])->assertSuccessful();
|
||||
});
|
||||
```
|
||||
|
||||
| Use | Instead of |
|
||||
|-----|------------|
|
||||
| `assertSuccessful()` | `assertStatus(200)` |
|
||||
| `assertNotFound()` | `assertStatus(404)` |
|
||||
| `assertForbidden()` | `assertStatus(403)` |
|
||||
|
||||
## Mocking
|
||||
|
||||
Import mock function before use: `use function Pest\Laravel\mock;`
|
||||
|
||||
## Datasets
|
||||
|
||||
Use datasets for repetitive tests (validation rules, etc.):
|
||||
|
||||
<!-- Pest Dataset Example -->
|
||||
```php
|
||||
it('has emails', function (string $email) {
|
||||
expect($email)->not->toBeEmpty();
|
||||
})->with([
|
||||
'james' => 'james@laravel.com',
|
||||
'taylor' => 'taylor@laravel.com',
|
||||
]);
|
||||
```
|
||||
|
||||
## Pest 5 Features
|
||||
|
||||
| Feature | Purpose |
|
||||
|---------|---------|
|
||||
| Tia (Test Impact Analysis) | Rerun only tests affected by recent changes |
|
||||
| Time-Balanced Sharding | Split tests across CI shards by execution time |
|
||||
| New Validation Expectations | `toBeEmail()`, `toBeUlid()`, `toBeIpAddress()`, and more |
|
||||
| Browser Testing | Full integration tests in real browsers |
|
||||
| Smoke Testing | Validate multiple pages quickly |
|
||||
| Visual Regression | Compare screenshots for visual changes |
|
||||
| Architecture Testing | Enforce code conventions |
|
||||
|
||||
### Tia (Test Impact Analysis)
|
||||
|
||||
Tia reruns only tests affected by recent changes and replays cached results for the rest, dramatically reducing suite duration:
|
||||
|
||||
<!-- Tia Example -->
|
||||
```shell
|
||||
./vendor/bin/pest --parallel --tia
|
||||
```
|
||||
|
||||
- Replayed tests are not skipped — cached tests store everything they produced, including covered lines and branches.
|
||||
- Detects Laravel, Symfony, Livewire, and Inertia automatically.
|
||||
|
||||
### New Validation Expectations
|
||||
|
||||
Pest 5 ships eight new validation matchers, all supporting `.not` negation:
|
||||
|
||||
<!-- Pest 5 Validation Expectations -->
|
||||
```php
|
||||
expect('nuno@pestphp.com')->toBeEmail();
|
||||
expect('01ARZ3NDEKTSV4RRFFQ69G5FAV')->toBeUlid();
|
||||
expect('192.168.1.1')->toBeIpAddress();
|
||||
expect('00:1a:2b:3c:4d:5e')->toBeMacAddress();
|
||||
expect('example.com')->toBeHostname();
|
||||
expect('example.co.uk')->toBeDomain();
|
||||
expect('Zm9vYmFy')->toBeBase64();
|
||||
expect('deadbeef')->toBeHexadecimal();
|
||||
```
|
||||
|
||||
### Time-Balanced Sharding
|
||||
|
||||
Distribute tests across CI shards by execution time rather than count:
|
||||
|
||||
<!-- Pest Sharding Example -->
|
||||
```shell
|
||||
./vendor/bin/pest --update-shards
|
||||
./vendor/bin/pest --shard=1/4
|
||||
```
|
||||
|
||||
Commit `tests/.pest/shards.json` to the repository so CI shards stay consistent.
|
||||
|
||||
### Browser Test Example
|
||||
|
||||
Browser tests run in real browsers for full integration testing:
|
||||
|
||||
- Browser tests live in `tests/Browser/`.
|
||||
- Use Laravel features like `Event::fake()`, `assertAuthenticated()`, and model factories.
|
||||
- Use `RefreshDatabase` for clean state per test.
|
||||
- Interact with page: click, type, scroll, select, submit, drag-and-drop, touch gestures.
|
||||
- Test on multiple browsers (Chrome, Firefox, Safari) if requested.
|
||||
- Test on different devices/viewports (iPhone 14 Pro, tablets) if requested.
|
||||
- Switch color schemes (light/dark mode) when appropriate.
|
||||
- Take screenshots or pause tests for debugging.
|
||||
|
||||
<!-- Pest Browser Test Example -->
|
||||
```php
|
||||
it('may reset the password', function () {
|
||||
Notification::fake();
|
||||
|
||||
$this->actingAs(User::factory()->create());
|
||||
|
||||
$page = visit('/sign-in');
|
||||
|
||||
$page->assertSee('Sign In')
|
||||
->assertNoJavaScriptErrors()
|
||||
->click('Forgot Password?')
|
||||
->fill('email', 'nuno@laravel.com')
|
||||
->click('Send Reset Link')
|
||||
->assertSee('We have emailed your password reset link!');
|
||||
|
||||
Notification::assertSent(ResetPassword::class);
|
||||
});
|
||||
```
|
||||
|
||||
### Smoke Testing
|
||||
|
||||
Quickly validate multiple pages have no JavaScript errors:
|
||||
|
||||
<!-- Pest Smoke Testing Example -->
|
||||
```php
|
||||
$pages = visit(['/', '/about', '/contact']);
|
||||
|
||||
$pages->assertNoJavaScriptErrors()->assertNoConsoleLogs();
|
||||
```
|
||||
|
||||
### Visual Regression Testing
|
||||
|
||||
Capture and compare screenshots to detect visual changes.
|
||||
|
||||
### Architecture Testing
|
||||
|
||||
<!-- Architecture Test Example -->
|
||||
```php
|
||||
arch('controllers')
|
||||
->expect('App\Http\Controllers')
|
||||
->toExtendNothing()
|
||||
->toHaveSuffix('Controller');
|
||||
```
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
- Not importing `use function Pest\Laravel\mock;` before using mock
|
||||
- Using `assertStatus(200)` instead of `assertSuccessful()`
|
||||
- Forgetting datasets for repetitive validation tests
|
||||
- Deleting tests without approval
|
||||
- Forgetting `assertNoJavaScriptErrors()` in browser tests
|
||||
- Prefixing `Feature/` or `Unit/` in `{name}` when using `make:test`
|
||||
|
|
@ -1,80 +0,0 @@
|
|||
---
|
||||
name: socialite-development
|
||||
description: "Manages OAuth social authentication with Laravel Socialite. Activate when adding social login providers; configuring OAuth redirect/callback flows; retrieving authenticated user details; customizing scopes or parameters; setting up community providers; testing with Socialite fakes; or when the user mentions social login, OAuth, Socialite, or third-party authentication."
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
|
||||
# Socialite Authentication
|
||||
|
||||
## Documentation
|
||||
|
||||
Use `search-docs` for detailed Socialite patterns and documentation (installation, configuration, routing, callbacks, testing, scopes, stateless auth).
|
||||
|
||||
## Available Providers
|
||||
|
||||
Built-in: `facebook`, `twitter`, `twitter-oauth-2`, `linkedin`, `linkedin-openid`, `google`, `github`, `gitlab`, `bitbucket`, `slack`, `slack-openid`, `twitch`
|
||||
|
||||
Community: 150+ additional providers at [socialiteproviders.com](https://socialiteproviders.com). For provider-specific setup, use `WebFetch` on `https://socialiteproviders.com/{provider-name}`.
|
||||
|
||||
Configuration key in `config/services.php` must match the driver name exactly — note the hyphenated keys: `twitter-oauth-2`, `linkedin-openid`, `slack-openid`.
|
||||
|
||||
Twitter/X: Use `twitter-oauth-2` (OAuth 2.0) for new projects. The legacy `twitter` driver is OAuth 1.0. Driver names remain unchanged despite the platform rebrand.
|
||||
|
||||
Community providers differ from built-in providers in the following ways:
|
||||
- Installed via `composer require socialiteproviders/{name}`
|
||||
- Must register via event listener — NOT auto-discovered like built-in providers
|
||||
- Use `search-docs` for the registration pattern
|
||||
|
||||
## Adding a Provider
|
||||
|
||||
### 1. Configure the provider
|
||||
|
||||
Add the provider's `client_id`, `client_secret`, and `redirect` to `config/services.php`. The config key must match the driver name exactly.
|
||||
|
||||
### 2. Create redirect and callback routes
|
||||
|
||||
Two routes are needed: one that calls `Socialite::driver('provider')->redirect()` to send the user to the OAuth provider, and one that calls `Socialite::driver('provider')->user()` to receive the callback and retrieve user details.
|
||||
|
||||
### 3. Authenticate and store the user
|
||||
|
||||
In the callback, use `updateOrCreate` to find or create a user record from the provider's response (`id`, `name`, `email`, `token`, `refreshToken`), then call `Auth::login()`.
|
||||
|
||||
### 4. Customize the redirect (optional)
|
||||
|
||||
- `scopes()` — merge additional scopes with the provider's defaults
|
||||
- `setScopes()` — replace all scopes entirely
|
||||
- `with()` — pass optional parameters (e.g., `['hd' => 'example.com']` for Google)
|
||||
- `asBotUser()` — Slack only; generates a bot token (`xoxb-`) instead of a user token (`xoxp-`). Must be called before both `redirect()` and `user()`. Only the `token` property will be hydrated on the user object.
|
||||
- `stateless()` — for API/SPA contexts where session state is not maintained
|
||||
|
||||
### 5. Verify
|
||||
|
||||
1. Config key matches driver name exactly (check the list above for hyphenated names)
|
||||
2. `client_id`, `client_secret`, and `redirect` are all present
|
||||
3. Redirect URL matches what is registered in the provider's OAuth dashboard
|
||||
4. Callback route handles denied grants (when user declines authorization)
|
||||
|
||||
Use `search-docs` for complete code examples of each step.
|
||||
|
||||
## Additional Features
|
||||
|
||||
Use `search-docs` for usage details on: `enablePKCE()`, `userFromToken($token)`, `userFromTokenAndSecret($token, $secret)` (OAuth 1.0), retrieving user details.
|
||||
|
||||
User object: `getId()`, `getName()`, `getEmail()`, `getAvatar()`, `getNickname()`, `token`, `refreshToken`, `expiresIn`, `approvedScopes`
|
||||
|
||||
## Testing
|
||||
|
||||
Socialite provides `Socialite::fake()` for testing redirects and callbacks. Use `search-docs` for faking redirects, callback user data, custom token properties, and assertion methods.
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
- Config key must match driver name exactly — hyphenated drivers need hyphenated keys (`linkedin-openid`, `slack-openid`, `twitter-oauth-2`). Mismatch silently fails.
|
||||
- Every provider needs `client_id`, `client_secret`, and `redirect` in `config/services.php`. Missing any one causes cryptic errors.
|
||||
- `scopes()` merges with defaults; `setScopes()` replaces all scopes entirely.
|
||||
- Missing `stateless()` in API/SPA contexts causes `InvalidStateException`.
|
||||
- Redirect URL in `config/services.php` must exactly match the provider's OAuth dashboard (including trailing slashes and protocol).
|
||||
- Do not pass `state`, `response_type`, `client_id`, `redirect_uri`, or `scope` via `with()` — these are reserved.
|
||||
- Community providers require event listener registration via `SocialiteWasCalled`.
|
||||
- `user()` throws when the user declines authorization. Always handle denied grants.
|
||||
|
|
@ -1,119 +0,0 @@
|
|||
---
|
||||
name: tailwindcss-development
|
||||
description: "Always invoke when the user's message includes 'tailwind' in any form. Also invoke for: building responsive grid layouts (multi-column card grids, product grids), flex/grid page structures (dashboards with sidebars, fixed topbars, mobile-toggle navs), styling UI components (cards, tables, navbars, pricing sections, forms, inputs, badges), adding dark mode variants, fixing spacing or typography, and Tailwind v3/v4 work. The core use case: writing or fixing Tailwind utility classes in HTML templates (Blade, JSX, Vue). Skip for backend PHP logic, database queries, API routes, JavaScript with no HTML/CSS component, CSS file audits, build tool configuration, and vanilla CSS."
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
|
||||
# Tailwind CSS Development
|
||||
|
||||
## Documentation
|
||||
|
||||
Use `search-docs` for detailed Tailwind CSS v4 patterns and documentation.
|
||||
|
||||
## Basic Usage
|
||||
|
||||
- Use Tailwind CSS classes to style HTML. Check and follow existing Tailwind conventions in the project before introducing new patterns.
|
||||
- Offer to extract repeated patterns into components that match the project's conventions (e.g., Blade, JSX, Vue).
|
||||
- Consider class placement, order, priority, and defaults. Remove redundant classes, add classes to parent or child elements carefully to reduce repetition, and group elements logically.
|
||||
|
||||
## Tailwind CSS v4 Specifics
|
||||
|
||||
- Always use Tailwind CSS v4 and avoid deprecated utilities.
|
||||
- `corePlugins` is not supported in Tailwind v4.
|
||||
|
||||
### CSS-First Configuration
|
||||
|
||||
In Tailwind v4, configuration is CSS-first using the `@theme` directive — no separate `tailwind.config.js` file is needed:
|
||||
|
||||
<!-- CSS-First Config -->
|
||||
```css
|
||||
@theme {
|
||||
--color-brand: oklch(0.72 0.11 178);
|
||||
}
|
||||
```
|
||||
|
||||
### Import Syntax
|
||||
|
||||
In Tailwind v4, import Tailwind with a regular CSS `@import` statement instead of the `@tailwind` directives used in v3:
|
||||
|
||||
<!-- v4 Import Syntax -->
|
||||
```diff
|
||||
- @tailwind base;
|
||||
- @tailwind components;
|
||||
- @tailwind utilities;
|
||||
+ @import "tailwindcss";
|
||||
```
|
||||
|
||||
### Replaced Utilities
|
||||
|
||||
Tailwind v4 removed deprecated utilities. Use the replacements shown below. Opacity values remain numeric.
|
||||
|
||||
| Deprecated | Replacement |
|
||||
|------------|-------------|
|
||||
| bg-opacity-* | bg-black/* |
|
||||
| text-opacity-* | text-black/* |
|
||||
| border-opacity-* | border-black/* |
|
||||
| divide-opacity-* | divide-black/* |
|
||||
| ring-opacity-* | ring-black/* |
|
||||
| placeholder-opacity-* | placeholder-black/* |
|
||||
| flex-shrink-* | shrink-* |
|
||||
| flex-grow-* | grow-* |
|
||||
| overflow-ellipsis | text-ellipsis |
|
||||
| decoration-slice | box-decoration-slice |
|
||||
| decoration-clone | box-decoration-clone |
|
||||
|
||||
## Spacing
|
||||
|
||||
Use `gap` utilities instead of margins for spacing between siblings:
|
||||
|
||||
<!-- Gap Utilities -->
|
||||
```html
|
||||
<div class="flex gap-8">
|
||||
<div>Item 1</div>
|
||||
<div>Item 2</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
## Dark Mode
|
||||
|
||||
If existing pages and components support dark mode, new pages and components must support it the same way, typically using the `dark:` variant:
|
||||
|
||||
<!-- Dark Mode -->
|
||||
```html
|
||||
<div class="bg-white dark:bg-gray-900 text-gray-900 dark:text-white">
|
||||
Content adapts to color scheme
|
||||
</div>
|
||||
```
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Flexbox Layout
|
||||
|
||||
<!-- Flexbox Layout -->
|
||||
```html
|
||||
<div class="flex items-center justify-between gap-4">
|
||||
<div>Left content</div>
|
||||
<div>Right content</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
### Grid Layout
|
||||
|
||||
<!-- Grid Layout -->
|
||||
```html
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
<div>Card 1</div>
|
||||
<div>Card 2</div>
|
||||
<div>Card 3</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
- Using deprecated v3 utilities (bg-opacity-*, flex-shrink-*, etc.)
|
||||
- Using `@tailwind` directives instead of `@import "tailwindcss"`
|
||||
- Trying to use `tailwind.config.js` instead of CSS `@theme` directive
|
||||
- Using margins for spacing between siblings instead of gap utilities
|
||||
- Forgetting to add dark mode variants when the project uses dark mode
|
||||
|
|
@ -1,80 +0,0 @@
|
|||
---
|
||||
name: wayfinder-development
|
||||
description: "Use this skill for Laravel Wayfinder which auto-generates typed functions for Laravel controllers and routes. ALWAYS use this skill when frontend code needs to call backend routes or controller actions. Trigger when: connecting any React/Vue/Svelte/Inertia frontend to Laravel controllers, routes, building end-to-end features with both frontend and backend, wiring up forms or links to backend endpoints, fixing route-related TypeScript errors, importing from @/actions or @/routes, or running wayfinder:generate. Use Wayfinder route functions instead of hardcoded URLs. Covers: wayfinder() vite plugin, .url()/.get()/.post()/.form(), query params, route model binding, tree-shaking. Do not use for backend-only task"
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
|
||||
# Wayfinder Development
|
||||
|
||||
## Documentation
|
||||
|
||||
Use `search-docs` for detailed Wayfinder patterns and documentation.
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### Generate Routes
|
||||
|
||||
Run after route changes if Vite plugin isn't installed:
|
||||
```bash
|
||||
php artisan wayfinder:generate --no-interaction
|
||||
```
|
||||
For form helpers, use `--with-form` flag:
|
||||
```bash
|
||||
php artisan wayfinder:generate --with-form --no-interaction
|
||||
```
|
||||
|
||||
### Import Patterns
|
||||
|
||||
<!-- Controller Action Imports -->
|
||||
```typescript
|
||||
// Named imports for tree-shaking (preferred)...
|
||||
import { show, store, update } from '@/actions/App/Http/Controllers/PostController'
|
||||
|
||||
// Named route imports...
|
||||
import { show as postShow } from '@/routes/post'
|
||||
```
|
||||
|
||||
### Common Methods
|
||||
|
||||
<!-- Wayfinder Methods -->
|
||||
```typescript
|
||||
// Get route object...
|
||||
show(1) // { url: "/posts/1", method: "get" }
|
||||
|
||||
// Get URL string...
|
||||
show.url(1) // "/posts/1"
|
||||
|
||||
// Specific HTTP methods...
|
||||
show.get(1)
|
||||
store.post()
|
||||
update.patch(1)
|
||||
destroy.delete(1)
|
||||
|
||||
// Form attributes for HTML forms...
|
||||
store.form() // { action: "/posts", method: "post" }
|
||||
|
||||
// Query parameters...
|
||||
show(1, { query: { page: 1 } }) // "/posts/1?page=1"
|
||||
```
|
||||
|
||||
## Wayfinder + Inertia
|
||||
|
||||
Use Wayfinder with the `<Form>` component:
|
||||
<!-- Wayfinder Form (Vue) -->
|
||||
```vue
|
||||
<Form v-bind="store.form()"><input name="title" /></Form>
|
||||
```
|
||||
|
||||
## Verification
|
||||
|
||||
1. Run `php artisan wayfinder:generate` to regenerate routes if Vite plugin isn't installed
|
||||
2. Check TypeScript imports resolve correctly
|
||||
3. Verify route URLs match expected paths
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
- Using default imports instead of named imports (breaks tree-shaking)
|
||||
- Forgetting to regenerate after route changes
|
||||
- Not using type-safe parameter objects for route model binding
|
||||
|
|
@ -1,301 +0,0 @@
|
|||
---
|
||||
description: Friday release ritual — create git tag, GitHub release (auto-generated changelog), and a customer-facing email draft (Cal.com style)
|
||||
allowed-tools: Bash, Write, Read, Skill
|
||||
---
|
||||
|
||||
You are running the Friday release ritual for TryPost. Four artifacts are produced:
|
||||
|
||||
1. A git tag (semver)
|
||||
2. A GitHub release with the **auto-generated** changelog (PR list + authors via GitHub's native generator — flat, technical, for developers)
|
||||
3. A **customer-facing email draft** in Cal.com style (themed prose, end-user voice, no commit/PR references)
|
||||
4. A **changelog thumbnail** (1200×630 PNG) rendered from the email's headline and themes, using the TryPost brand template
|
||||
|
||||
Plus local mirrors in `releases/<version>/` (changelog, email, and thumbnail), versioned via the artifacts PR.
|
||||
|
||||
**Always confirm with the user before any push/tag/release.**
|
||||
|
||||
## Context (auto-loaded)
|
||||
|
||||
- Current branch: !`git branch --show-current`
|
||||
- Working tree: !`git status --porcelain`
|
||||
- Latest tag: !`git describe --tags --abbrev=0 2>/dev/null || echo "(none)"`
|
||||
- Repo (owner/name): !`gh repo view --json nameWithOwner -q .nameWithOwner 2>/dev/null || echo "(no gh)"`
|
||||
- Local vs origin/main: !`git fetch --quiet origin main 2>/dev/null; git rev-list --left-right --count HEAD...origin/main 2>/dev/null || echo "0 0"`
|
||||
- Commits since latest tag (or all if no tag): !`LAST_TAG=$(git describe --tags --abbrev=0 2>/dev/null); if [ -z "$LAST_TAG" ]; then git log --pretty=format:"%H%x09%s" --reverse; else git log "$LAST_TAG"..HEAD --pretty=format:"%H%x09%s" --reverse; fi`
|
||||
|
||||
## Workflow
|
||||
|
||||
### Step 1 — Pre-flight checks
|
||||
|
||||
Stop and tell the user if any of these fail:
|
||||
|
||||
- Current branch must be `main`. Else: ask user to `git checkout main`.
|
||||
- Working tree must be clean. Else: ask user to commit/stash.
|
||||
- Local in sync with `origin/main` (rev-list count `0 0`). Else: ask user to pull/push.
|
||||
- Commits-since-tag list must be non-empty. Else: "Nothing new since the last tag."
|
||||
|
||||
### Step 2 — Determine next version
|
||||
|
||||
TryPost uses **sequential numbering with rollover at 9** — not standard semver. Do not parse conventional commits to choose the bump. Every release is the next sequential number, whatever the commits look like.
|
||||
|
||||
1. If no previous tag exists → next version = **`v1.0.0`** (first release ever).
|
||||
2. Otherwise, parse the latest tag as `vMAJOR.MINOR.PATCH` and increment by these rules:
|
||||
- `patch += 1`
|
||||
- If `patch` reaches `10`: set `patch = 0`, `minor += 1`
|
||||
- If `minor` reaches `10`: set `minor = 0`, `major += 1`
|
||||
3. Re-prefix with `v`.
|
||||
|
||||
Examples:
|
||||
|
||||
| From | To |
|
||||
|---|---|
|
||||
| (no tag) | v1.0.0 |
|
||||
| v1.0.0 | v1.0.1 |
|
||||
| v1.0.8 | v1.0.9 |
|
||||
| v1.0.9 | v1.1.0 |
|
||||
| v1.5.7 | v1.5.8 |
|
||||
| v1.9.8 | v1.9.9 |
|
||||
| v1.9.9 | v2.0.0 |
|
||||
|
||||
There is no manual override — the next version is whatever the rule above produces. If a release needs a different version for some special reason, the user must create the tag manually outside this command.
|
||||
|
||||
### Step 3 — Preview the changelog (GitHub native format)
|
||||
|
||||
Use GitHub's release-notes generator API to produce the changelog **without creating anything yet**:
|
||||
|
||||
```bash
|
||||
gh api -X POST "repos/{OWNER}/{REPO}/releases/generate-notes" \
|
||||
-f tag_name="<new_version>" \
|
||||
-f target_commitish="main" \
|
||||
-f previous_tag_name="<latest_tag>" \
|
||||
--jq '.body'
|
||||
```
|
||||
|
||||
For the first release ever (no previous tag), omit the `previous_tag_name` flag — GitHub falls back to the initial commit.
|
||||
|
||||
The body already contains:
|
||||
- `<subject> by @<author> in #<PR>` lines
|
||||
- "New Contributors" section when applicable
|
||||
- `Full Changelog: ...` compare link
|
||||
|
||||
**Do not modify it.** The GitHub-native format is the goal.
|
||||
|
||||
### Step 4 — Draft the customer email (Cal.com style)
|
||||
|
||||
This email is for **end users of TryPost** — non-developers, paying customers, trial users. It must **NOT** reference: commits, PRs, authors, SHAs, conventional commit scopes, version control concepts, internal class names, file paths.
|
||||
|
||||
Read the commits only as **internal source material**. Translate to user-facing language.
|
||||
|
||||
#### Structure
|
||||
|
||||
```markdown
|
||||
---
|
||||
subject: "Changelog <version> — <improvement 1>, <improvement 2> and more..."
|
||||
---
|
||||
|
||||
# Changelog <version> — <improvement 1>, <improvement 2> and more...
|
||||
|
||||
By TryPost Product Team • [Release <version>](https://github.com/<OWNER>/<REPO>/releases/tag/<version>)
|
||||
|
||||
Hello! Welcome to this week's update. Here's what's new in TryPost.
|
||||
|
||||
## <Outcome the reader gets, or the symptom that is gone>
|
||||
|
||||
<2-4 sentences of concrete narrative — what changed, why a user should care, what they'll notice. Open on what the reader experienced ("you may have watched it go out twice"), not on the internal cause. No marketing puffery.>
|
||||
|
||||
## <second outcome>
|
||||
|
||||
<same>
|
||||
|
||||
## <third outcome — only if there are genuinely 3 themes worth of work>
|
||||
|
||||
<same>
|
||||
|
||||
## New features
|
||||
|
||||
- <user-facing one-liner — what they can now do>
|
||||
- <...>
|
||||
|
||||
## Fixes
|
||||
|
||||
- <user-facing one-liner — what no longer breaks>
|
||||
- <...>
|
||||
|
||||
Cheers,
|
||||
Paulo from TryPost.it
|
||||
|
||||
---
|
||||
|
||||
You're receiving this because you subscribed.
|
||||
[Unsubscribe]({{unsubscribe_url}})
|
||||
```
|
||||
|
||||
**Always link the GitHub release from the byline** — make `Release <version>` a link to `https://github.com/<OWNER>/<REPO>/releases/tag/<version>` (as shown above). It gives developer-minded readers the raw PR-level changelog without cluttering the body.
|
||||
|
||||
**Always end with the unsubscribe footer** — the `---` separator, the "You're receiving this because you subscribed." line, and an `[Unsubscribe]({{unsubscribe_url}})` link below the signature. Keep `{{unsubscribe_url}}` as a literal placeholder; the email sending tool fills it in. This footer is required on every customer email.
|
||||
|
||||
#### Section headers
|
||||
|
||||
A theme header names the outcome the reader gets or the symptom that is gone. Sentence case. It has to make sense to someone who never saw the bug report.
|
||||
|
||||
- ❌ `## Publishing that finishes what it started` (writerly; says nothing concrete)
|
||||
- ❌ `## Your Asset Library, from anywhere` (area label dressed up)
|
||||
- ✅ `## Your long videos stop posting twice`
|
||||
- ✅ `## The Facebook Pages that wouldn't connect`
|
||||
|
||||
**Section order must match the subject order.** The subject promises a sequence. A reader who opens on a different topic than the one that got them to click feels the mismatch even if they can't name it.
|
||||
|
||||
#### Theme grouping (AI clusters by user impact)
|
||||
|
||||
Read all commits since the last tag and cluster into **2-3 user-facing themes**. Use whatever frame makes the changes feel coherent to a customer, not to a developer.
|
||||
|
||||
**Good themes** (end-user framing):
|
||||
- "Trial protection" — bundles billing/Stripe Radar work
|
||||
- "Reliable Facebook posting" — bundles Facebook fixes
|
||||
- "Faster scheduling" — bundles queue/post improvements
|
||||
- "Better post editor" — bundles UI changes to the post composer
|
||||
|
||||
**Bad themes** (internal framing — never use these):
|
||||
- "Refactoring"
|
||||
- "Dependency updates"
|
||||
- "Feature commits" / "Fix commits"
|
||||
- "Backend improvements"
|
||||
|
||||
If there are fewer than 3 themeable groups, use 2 or just 1. Don't pad. Internal-only changes (chore, CI, refactor, deps) usually shouldn't appear at all — fold the user-visible ones into "Fixes" with a user-voice rewrite, drop the rest.
|
||||
|
||||
**Order themes by reach, not by newness.** The first theme goes to whatever the largest share of subscribers will actually feel. A fix that unblocks a whole platform for everyone who uses it outranks a feature only integrators can reach, even though the feature is the newer work. Rank by how many people were affected.
|
||||
|
||||
**Check who a theme really reaches before you headline it.** Exposing an existing in-app capability over the API or MCP is new for integrators only — everyone else already had it in the UI. Headlining it as if the capability itself were new misleads the majority. Either qualify the section in its first sentence ("If you build against the TryPost API or connect an AI assistant...") and say plainly that the in-app path already worked, or demote it under a theme with broader reach.
|
||||
|
||||
#### Bullet rules for "New features" / "Fixes"
|
||||
|
||||
Rewrite each item in **user voice**, not commit voice:
|
||||
|
||||
- ❌ "fix(facebook): send Graph API requests as form-urlencoded"
|
||||
- ✅ "Fixed an issue where multi-image Facebook posts could fail to publish"
|
||||
|
||||
- ❌ "feat(billing): charge one-time trial setup fee at Stripe Checkout"
|
||||
- ✅ (Probably its own theme, not a bullet — billing is a big user-facing topic)
|
||||
|
||||
- ❌ "chore(deps): bump axios to 1.13.5"
|
||||
- ✅ (Skip entirely — pure internal)
|
||||
|
||||
If a commit has no user-visible effect, **omit it**. Don't pad the email.
|
||||
|
||||
**Never repeat a theme section in the bullets.** "New features" and "Fixes" are for what did *not* earn its own section. If duplicate Instagram posts got three paragraphs above, they don't also get a bullet — the reader meets the same fact twice and the lists stop being scannable. Write the sections first, then list only what is left over.
|
||||
|
||||
#### Subject line
|
||||
|
||||
Pattern: `Changelog <version> — <improvement 1>, <improvement 2> and more...`
|
||||
|
||||
Each slot must name **what got better for the reader**, never the area it happened in. The area is where the work landed; the improvement is what they can now do, or what stopped hurting. A subject built from area labels tells a customer nothing — they already know TryPost has an Asset Library.
|
||||
|
||||
- ❌ `Changelog v1.0.8 — Publishing that finishes, Facebook Pages, Asset Library` (a writerly abstraction plus two bare area labels)
|
||||
- ❌ `Changelog v1.0.8 — No duplicate posts, Facebook Pages that connect` (still abstract: "no duplicate posts" reads like a new dedup feature rather than a fix, and the second half is awkward)
|
||||
- ✅ `Changelog v1.0.8 — Facebook Pages finally connect, reuse your media and more...`
|
||||
|
||||
Rules:
|
||||
|
||||
- **Two named improvements plus `and more...` beats three cramped ones.** The trailing `and more...` carries the rest of the release and buys the two named slots enough room to be specific.
|
||||
- **The first slot goes to the widest reach.** Same ranking as the themes: most subscribers affected wins, even when that is a bug fix and the release also shipped a shiny feature.
|
||||
- Plain words like `finally`, `stop`, `no longer` are good — they read as an honest founder, not a marketer.
|
||||
- Don't put "TryPost" in the subject — the email already comes from the TryPost sender, so it's redundant.
|
||||
- Cap around 80 chars.
|
||||
|
||||
### Step 5 — Humanize the email prose
|
||||
|
||||
Run the email body through the `humanizer` skill before previewing:
|
||||
|
||||
1. Invoke the `Skill` tool with `skill: humanizer` and pass the draft email body plus this context: *"This is a customer-facing changelog email for TryPost (social media scheduler SaaS). Tone: developer founder writing to early users on a Friday — warm, specific, no marketing puffery. Cal.com style. Keep the existing structure (subject frontmatter, section headers, bullets, signature, unsubscribe footer). Do not strip section headers, the 'Cheers, Paulo from TryPost.it' signature, or the unsubscribe footer."*
|
||||
2. Replace the draft email body with the humanized version.
|
||||
|
||||
**Do NOT humanize:**
|
||||
- The changelog from Step 3 (flat commit list, no prose).
|
||||
- The subject line frontmatter.
|
||||
- The literal signature `Cheers,\nPaulo from TryPost.it` — keep it exact.
|
||||
- The unsubscribe footer (`---`, "You're receiving this because you subscribed.", `[Unsubscribe]({{unsubscribe_url}})`) — keep it exact, below the signature.
|
||||
|
||||
The humanizer skill itself covers all patterns. Trust it.
|
||||
|
||||
### Step 5b — Render the changelog thumbnail
|
||||
|
||||
Derive these inputs from the release. The **headline and the chips play different roles — never make one restate the other**:
|
||||
|
||||
- **version** — always pass the release version (e.g. `v1.0.6`). It is stamped in the badge as a mono segment (`★ CHANGELOG | v1.0.6`) so every release image is consistent. Not optional.
|
||||
- **headline** — a crafted marketing hero line (2-6 words, at most two lines), in the voice of the marketing site's hero (`Run your social media on autopilot`). It sells the *benefit* of the release's biggest wins; it is the loudest thing on the image. Do **NOT** paste the subject line, and do **NOT** just list the theme/chip words — the chips already name the areas, so the headline sits one level above them. Read the email's themes **and** the "New features" bullets, find the strongest story, and write a fresh benefit line. A little rhythm helps (a parallel pair reads well, e.g. `Speak every language, reach every reader`). Sentence case, no version number in the headline itself (it lives in the badge), no period.
|
||||
- ❌ `Your language, mobile, and per-image alt text` (this is just the chip labels)
|
||||
- ✅ `Speak every language, reach every reader` (benefit-driven, distinct from the chips)
|
||||
- **underline** — a short emphasis phrase *inside* the headline (1-3 words) to carry the hand-drawn violet squiggle, usually the last / most important phrase (e.g. `every reader`). Must appear in the headline verbatim. Optional; omit for no squiggle.
|
||||
- **themes** — 2-4 short chip labels naming the concrete areas that shipped, condensed to 1-2 words each (e.g. `Languages`, `Mobile`, `Alt text & previews`). These are secondary supporting labels, rendered smaller than the headline; the template auto-colors them (violet / green / sky / orange / rose, in order). Keep them concrete and distinct from the headline's wording. **Order the chips to match the email's section order**, so the image and the email tell the story in the same sequence. Chips are the one place a bare area label is correct: the headline sells the benefit, the chips name where it landed.
|
||||
|
||||
Create the directory and render the thumbnail so the user can preview it before confirming:
|
||||
|
||||
```bash
|
||||
mkdir -p releases/<version>
|
||||
node .claude/release-assets/render-thumbnail.mjs \
|
||||
--version "<version>" \
|
||||
--headline "<headline>" \
|
||||
--underline "<emphasis phrase>" \
|
||||
--themes "<label 1>,<label 2>,<label 3>" \
|
||||
--out releases/<version>/thumbnail.png
|
||||
```
|
||||
|
||||
This uses the shared brand template (`.claude/release-assets/thumbnail.template.html`) + TryPost logo. It mirrors the marketing-site hero / OG image: a warm cream→lavender wash, an ink dot-grid, an Instrument Serif headline with a hand-drawn violet squiggle under the emphasis phrase, an amber "Changelog" sticker badge with the version stamped in mono, and colored ink-bordered theme chips with solid offset shadows. 1200×630. It needs Playwright + chromium (already installed for browser tests). If the render fails, report and stop before tagging.
|
||||
|
||||
### Step 6 — Confirm with the user
|
||||
|
||||
Show:
|
||||
1. **Proposed version** (e.g., `v1.0.9 → v1.1.0` — sequential rollover at 9).
|
||||
2. **Changelog preview** (Step 3 output).
|
||||
3. **Email preview**: subject line + full body (post-humanizer).
|
||||
4. **Thumbnail**: `releases/<version>/thumbnail.png` (already rendered in Step 5b — tell the user they can open it to preview).
|
||||
5. **Files that will be created/pushed**:
|
||||
- Tag `<version>` (pushed to origin)
|
||||
- GitHub release `<version>`
|
||||
- `releases/<version>/changelog.md`
|
||||
- `releases/<version>/email.md`
|
||||
- `releases/<version>/thumbnail.png`
|
||||
- Branch `chore/release-<version>-artifacts` + a PR versioning the three files above
|
||||
|
||||
Then ask: **"Create the tag, publish the release, and open the PR with the artifacts?"**
|
||||
|
||||
Do **not** proceed without explicit yes.
|
||||
|
||||
### Step 7 — Execute
|
||||
|
||||
After confirmation, in this exact order. Steps 4–6 (tag + release) run from `main` so the tag stays on the released `main` commit; steps 7–8 version the artifacts on a separate branch and open a PR.
|
||||
|
||||
1. Create local directory: `mkdir -p releases/<version>` (already created in Step 5b).
|
||||
2. Write `releases/<version>/changelog.md` with the Step 3 content (raw GitHub markdown).
|
||||
3. Write `releases/<version>/email.md` with frontmatter + humanized body.
|
||||
(`releases/<version>/thumbnail.png` was already rendered in Step 5b.)
|
||||
4. From `main`, create the annotated tag: `git tag -a <version> -m "Release <version>"`
|
||||
5. Push tag: `git push origin <version>`
|
||||
6. Create the GitHub release using the changelog file as body:
|
||||
```bash
|
||||
gh release create <version> --title "<version>" --notes-file releases/<version>/changelog.md
|
||||
```
|
||||
7. Version the artifacts on a branch (the three files carry over from the working tree) and push:
|
||||
```bash
|
||||
git checkout -b chore/release-<version>-artifacts
|
||||
git add releases/<version>/changelog.md releases/<version>/email.md releases/<version>/thumbnail.png
|
||||
git commit -m "chore(release): add <version> changelog, customer email, and thumbnail artifacts"
|
||||
git push -u origin chore/release-<version>-artifacts
|
||||
```
|
||||
8. Open the PR against `main` (body: what the three files are + a link to the GitHub release):
|
||||
```bash
|
||||
gh pr create --base main --head chore/release-<version>-artifacts \
|
||||
--title "chore(release): <version> changelog, customer email + thumbnail artifacts" \
|
||||
--body "<short body — the three artifact files + link to the release>"
|
||||
```
|
||||
9. Report to the user:
|
||||
- GitHub release URL (from `gh release` output)
|
||||
- PR URL (from `gh pr create` output)
|
||||
- Local paths: `releases/<version>/changelog.md`, `releases/<version>/email.md`, `releases/<version>/thumbnail.png`
|
||||
|
||||
### On failure
|
||||
|
||||
- `git push origin <version>` fails: report the exact error, leave the local tag in place, do not retry destructively.
|
||||
- `gh release create` fails: the tag is already pushed; tell the user they can recreate manually with `gh release create <version> --title "<version>" --notes-file releases/<version>/changelog.md`.
|
||||
- `git push` / `gh pr create` for the artifacts branch fails: the tag and GitHub release are already live; report the error and tell the user they can open the PR manually from `chore/release-<version>-artifacts`.
|
||||
- `Skill`, `Write`, or thumbnail render failure during artifact prep: report and stop. Do not push the tag without the artifacts being prepared.
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 11 KiB |
|
|
@ -1,99 +0,0 @@
|
|||
// Render a release changelog thumbnail (1200x630 PNG) from the shared template.
|
||||
//
|
||||
// Usage:
|
||||
// node .claude/release-assets/render-thumbnail.mjs \
|
||||
// --headline "Your language, mobile, and per-image alt text" \
|
||||
// --underline "alt text" \
|
||||
// --themes "Languages,Mobile,Alt text & previews" \
|
||||
// --out releases/v1.0.6/thumbnail.png
|
||||
//
|
||||
// Optional:
|
||||
// --version "v1.0.6" — stamped in the badge as a mono version segment.
|
||||
// --badge "Changelog" (default) — the amber sticker label, top-right.
|
||||
// --underline "phrase" — a phrase inside the headline to get the hand-drawn
|
||||
// violet squiggle (mirrors the marketing-site hero).
|
||||
//
|
||||
// Playwright is resolved from the repo's node_modules, so the script works
|
||||
// regardless of where it is invoked.
|
||||
|
||||
import { createRequire } from 'module';
|
||||
import { readFileSync, writeFileSync, unlinkSync } from 'fs';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { dirname, join } from 'path';
|
||||
import { tmpdir } from 'os';
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const repoRoot = join(here, '..', '..');
|
||||
const require = createRequire(join(repoRoot, 'package.json'));
|
||||
const { chromium } = require('playwright');
|
||||
|
||||
const args = {};
|
||||
for (let i = 2; i < process.argv.length; i += 2) {
|
||||
args[process.argv[i].replace(/^--/, '')] = process.argv[i + 1];
|
||||
}
|
||||
|
||||
if (!args.headline || !args.out) {
|
||||
console.error('usage: render-thumbnail.mjs --headline "..." --themes "a,b,c" --out path.png [--version "v1.0.6"] [--underline "phrase"] [--badge "Changelog"]');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const escapeHtml = (value) =>
|
||||
String(value)
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('"', '"');
|
||||
|
||||
// Hand-drawn violet squiggle under an emphasis phrase — same path the hero uses.
|
||||
const squiggle = (phrase) =>
|
||||
`<span class="ul">${phrase}<svg class="squiggle" viewBox="0 0 200 12" preserveAspectRatio="none" fill="none" stroke="currentColor" stroke-width="4" stroke-linecap="round" aria-hidden="true"><path d="M 5 6 Q 25 0, 50 6 T 100 6 T 150 6 T 195 6" /></svg></span>`;
|
||||
|
||||
let headlineHtml = escapeHtml(args.headline);
|
||||
if (args.underline) {
|
||||
const escapedPhrase = escapeHtml(args.underline);
|
||||
if (headlineHtml.includes(escapedPhrase)) {
|
||||
headlineHtml = headlineHtml.replace(escapedPhrase, squiggle(escapedPhrase));
|
||||
}
|
||||
}
|
||||
|
||||
const themes = (args.themes ?? '')
|
||||
.split(',')
|
||||
.map((theme) => theme.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
const chips = themes
|
||||
.map((theme) => `<span class="chip">${escapeHtml(theme)}</span>`)
|
||||
.join('\n ');
|
||||
|
||||
const star = `<svg class="star" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 2l2.9 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l7.1-1.01z" /></svg>`;
|
||||
let badgeInner = `<span class="label">${star}${escapeHtml(args.badge ?? 'Changelog')}</span>`;
|
||||
if (args.version) {
|
||||
badgeInner += `<span class="ver">${escapeHtml(args.version)}</span>`;
|
||||
}
|
||||
|
||||
const logoDataUri = `data:image/png;base64,${readFileSync(join(here, 'logo.png')).toString('base64')}`;
|
||||
|
||||
const html = readFileSync(join(here, 'thumbnail.template.html'), 'utf8')
|
||||
.replace('{{LOGO}}', logoDataUri)
|
||||
.replace('{{BADGE_INNER}}', badgeInner)
|
||||
.replace('{{HEADLINE}}', headlineHtml)
|
||||
.replace('{{CHIPS}}', chips);
|
||||
|
||||
const tmpFile = join(tmpdir(), `trypost-thumbnail-${process.pid}.html`);
|
||||
writeFileSync(tmpFile, html);
|
||||
|
||||
const browser = await chromium.launch();
|
||||
try {
|
||||
const page = await browser.newPage({
|
||||
viewport: { width: 1200, height: 630 },
|
||||
deviceScaleFactor: 2,
|
||||
});
|
||||
await page.goto(`file://${tmpFile}`, { waitUntil: 'networkidle' });
|
||||
await page.evaluate(() => document.fonts.ready);
|
||||
await page.screenshot({ path: args.out });
|
||||
} finally {
|
||||
await browser.close();
|
||||
unlinkSync(tmpFile);
|
||||
}
|
||||
|
||||
console.log('wrote', args.out);
|
||||
|
|
@ -1,128 +0,0 @@
|
|||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link href="https://fonts.googleapis.com/css2?family=Figtree:wght@300..900&family=Instrument+Serif:ital@0;1&family=JetBrains+Mono:wght@400;500;700&display=swap" rel="stylesheet" />
|
||||
<style>
|
||||
/* TryPost brand thumbnail — mirrors the marketing-site hero / OG image:
|
||||
warm cream + ink + signature violet, soft peach→lavender wash, ink
|
||||
dot-grid, Instrument Serif headline with a hand-drawn violet squiggle,
|
||||
and ink-bordered sticker cards with Gumroad-style solid offset shadows.
|
||||
Tokens from trypost-site assets/css/tailwind.css. */
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
html, body { width: 1200px; height: 630px; }
|
||||
body {
|
||||
font-family: 'Figtree', ui-sans-serif, system-ui, sans-serif;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
background: #faf8f5;
|
||||
color: #0a0a0a;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
/* Broad peach (bottom-left) → lavender (top-right) wash. */
|
||||
.wash {
|
||||
position: absolute; inset: 0; pointer-events: none;
|
||||
background: linear-gradient(118deg,
|
||||
rgba(254,215,170,0.34) 0%,
|
||||
rgba(250,248,245,0) 40%,
|
||||
rgba(250,248,245,0) 58%,
|
||||
rgba(196,181,253,0.46) 100%);
|
||||
}
|
||||
/* Soft glow blobs — violet top-right, warm amber bottom-left. */
|
||||
.blob { position: absolute; border-radius: 999px; pointer-events: none; filter: blur(36px); }
|
||||
.blob-violet { top: -160px; right: -120px; width: 560px; height: 560px;
|
||||
background: radial-gradient(circle, rgba(196,181,253,0.60) 0%, rgba(196,181,253,0) 70%); }
|
||||
.blob-warm { bottom: -190px; left: -150px; width: 540px; height: 540px;
|
||||
background: radial-gradient(circle, rgba(253,215,170,0.55) 0%, rgba(253,215,170,0) 70%); }
|
||||
.blob-fuchsia { bottom: 60px; left: 120px; width: 320px; height: 320px;
|
||||
background: radial-gradient(circle, rgba(245,208,254,0.35) 0%, rgba(245,208,254,0) 70%); }
|
||||
/* Ink dot-grid (over cream, softened by the blobs). */
|
||||
.grid {
|
||||
position: absolute; inset: 0; pointer-events: none; opacity: 0.07;
|
||||
background-image: radial-gradient(circle, #0a0a0a 1px, transparent 1px);
|
||||
background-size: 28px 28px;
|
||||
}
|
||||
.frame {
|
||||
position: relative; z-index: 1;
|
||||
height: 100%; padding: 74px 84px;
|
||||
display: flex; flex-direction: column; justify-content: space-between;
|
||||
}
|
||||
.top { display: flex; align-items: center; justify-content: space-between; }
|
||||
.logo { height: 36px; width: auto; }
|
||||
/* "Changelog" sticker — segmented ticket: amber label + mono version, one
|
||||
ink-bordered pill with an offset shadow (mirrors the site's gold
|
||||
"OPEN SOURCE" sticker). The version is always stamped for consistency. */
|
||||
.badge {
|
||||
display: inline-flex; align-items: stretch;
|
||||
border: 2.5px solid #0a0a0a; border-radius: 10px;
|
||||
box-shadow: 4px 4px 0 0 #0a0a0a; overflow: hidden;
|
||||
}
|
||||
.badge .label {
|
||||
display: inline-flex; align-items: center; gap: 9px;
|
||||
background: #fde68a; color: #0a0a0a;
|
||||
padding: 10px 17px;
|
||||
font-size: 15px; font-weight: 900;
|
||||
text-transform: uppercase; letter-spacing: 0.16em;
|
||||
}
|
||||
.badge .star { width: 16px; height: 16px; display: block; }
|
||||
.badge .ver {
|
||||
display: inline-flex; align-items: center;
|
||||
background: #ffffff; color: #0a0a0a;
|
||||
padding: 10px 15px;
|
||||
font-family: 'JetBrains Mono', ui-monospace, monospace;
|
||||
font-size: 15px; font-weight: 700; letter-spacing: 0.01em;
|
||||
border-left: 2.5px solid #0a0a0a;
|
||||
}
|
||||
.body { max-width: 1000px; }
|
||||
h1 {
|
||||
font-family: 'Instrument Serif', Georgia, serif;
|
||||
font-weight: 400; font-size: 88px; line-height: 1.04;
|
||||
letter-spacing: -0.02em; color: #0a0a0a; text-wrap: balance;
|
||||
}
|
||||
/* Emphasis phrase carrying the hand-drawn squiggle. */
|
||||
.ul { position: relative; display: inline-block; white-space: nowrap; }
|
||||
.ul > .squiggle {
|
||||
position: absolute; left: 0; right: 0; bottom: -0.16em;
|
||||
width: 100%; height: 0.34em; color: #8b5cf6;
|
||||
}
|
||||
.themes { display: flex; gap: 16px; flex-wrap: wrap; align-items: center; }
|
||||
/* Theme chips — colored sticker cards (brand pastels), ink border, offset
|
||||
shadow, ink text, hand-placed tilt (echoes the floating platform / composer
|
||||
stickers in the hero — bg-violet-300 ... text-foreground). Secondary to the
|
||||
headline: smaller and lighter in weight. */
|
||||
.chip {
|
||||
padding: 10px 18px; border-radius: 10px;
|
||||
color: #0a0a0a;
|
||||
border: 2.5px solid #0a0a0a;
|
||||
box-shadow: 3px 3px 0 0 #0a0a0a;
|
||||
font-size: 18px; font-weight: 600;
|
||||
}
|
||||
.chip:nth-child(1) { background: #ddd6fe; transform: rotate(-2deg); } /* violet-200 */
|
||||
.chip:nth-child(2) { background: #bbf7d0; transform: rotate(1.5deg); } /* green-200 */
|
||||
.chip:nth-child(3) { background: #bae6fd; transform: rotate(-1deg); } /* sky-200 */
|
||||
.chip:nth-child(4) { background: #fed7aa; transform: rotate(2deg); } /* orange-200 */
|
||||
.chip:nth-child(5) { background: #fecdd3; transform: rotate(-1.5deg); }/* rose-200 */
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wash"></div>
|
||||
<div class="blob blob-violet"></div>
|
||||
<div class="blob blob-warm"></div>
|
||||
<div class="blob blob-fuchsia"></div>
|
||||
<div class="grid"></div>
|
||||
<div class="frame">
|
||||
<div class="top">
|
||||
<img class="logo" src="{{LOGO}}" alt="TryPost" />
|
||||
<span class="badge">{{BADGE_INNER}}</span>
|
||||
</div>
|
||||
|
||||
<div class="body">
|
||||
<h1>{{HEADLINE}}</h1>
|
||||
</div>
|
||||
|
||||
<div class="themes">{{CHIPS}}</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -1,483 +0,0 @@
|
|||
---
|
||||
name: ai-sdk-development
|
||||
description: TRIGGER when working with ai-sdk which is Laravel official first-party AI SDK. Activate when building, editing AI agents, chatbots, text generation, image generation, audio/TTS, transcription/STT, embeddings, RAG, vector stores, reranking, structured output, streaming, conversation memory, tools, queueing, broadcasting, and provider failover across OpenAI, Anthropic, Gemini, Azure, Groq, xAI, DeepSeek, Mistral, Ollama, ElevenLabs, Cohere, Jina, and VoyageAI. Invoke when the user references ai-sdk, the `Laravel\Ai\` namespace, or this project's AI features — not for other AI packages used directly.
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
|
||||
# Developing with the Laravel AI SDK
|
||||
|
||||
The Laravel AI SDK (`laravel/ai`) is the official AI package for Laravel, providing a unified API for agents, images, audio, transcription, embeddings, reranking, vector stores, and file management across multiple AI providers.
|
||||
|
||||
## Searching the Documentation
|
||||
|
||||
This package is new. Always search the documentation before implementing any feature. Never guess at APIs — the documentation is the single source of truth.
|
||||
|
||||
- Use broad, simple queries that match the documentation section headings below.
|
||||
- Do not add package names to queries — package information is shared automatically. Use `test agent fake`, not `laravel ai test agent fake`.
|
||||
- Run multiple queries at once — the most relevant results are returned first.
|
||||
|
||||
### Documentation Sections
|
||||
|
||||
Use these section headings as query terms for accurate results:
|
||||
|
||||
- Introduction, Installation, Configuration, Provider Support
|
||||
- Agents: Prompting, Conversation Context, Structured Output, Attachments, Streaming, Broadcasting, Queueing, Tools, Provider Tools, Middleware, Anonymous Agents, Agent Configuration
|
||||
- Images
|
||||
- Audio (TTS)
|
||||
- Transcription (STT)
|
||||
- Embeddings: Querying Embeddings, Caching Embeddings
|
||||
- Reranking
|
||||
- Files
|
||||
- Vector Stores: Adding Files to Stores
|
||||
- Failover
|
||||
- Testing: Agents, Images, Audio, Transcriptions, Embeddings, Reranking, Files, Vector Stores
|
||||
- Events
|
||||
|
||||
## Decision Workflow
|
||||
|
||||
Determine the right entry point before writing code:
|
||||
|
||||
Text generation or chat? → Agent class with `Promptable` trait
|
||||
Chat with conversation history? → Agent + `Conversational` interface (manual) or `RemembersConversations` trait (automatic)
|
||||
Structured JSON output? → Agent + `HasStructuredOutput` interface
|
||||
Image generation? → `Image::of()->generate()`
|
||||
Audio synthesis? → `Audio::of()->generate()`
|
||||
Transcription? → `Transcription::fromPath()->generate()`
|
||||
Embeddings? → `Embeddings::for()->generate()`
|
||||
Reranking? → `Reranking::of()->rerank()`
|
||||
File storage? → `Document::fromPath()->put()`
|
||||
Vector stores? → `Stores::create()`
|
||||
|
||||
## Basic Usage Examples
|
||||
|
||||
### Agents
|
||||
|
||||
```php
|
||||
use Laravel\Ai\Contracts\Agent;
|
||||
use Laravel\Ai\Enums\Lab;
|
||||
use Laravel\Ai\Promptable;
|
||||
|
||||
class SalesCoach implements Agent
|
||||
{
|
||||
use Promptable;
|
||||
|
||||
public function instructions(): string
|
||||
{
|
||||
return 'You are a sales coach.';
|
||||
}
|
||||
}
|
||||
|
||||
// Prompting
|
||||
$response = (new SalesCoach)->prompt('Analyze this transcript...');
|
||||
echo $response->text;
|
||||
|
||||
// Container resolution with dependency injection
|
||||
$agent = SalesCoach::make(user: $user);
|
||||
|
||||
// Override provider, model, or timeout per-prompt
|
||||
$response = (new SalesCoach)->prompt(
|
||||
'Analyze this transcript...',
|
||||
provider: Lab::Anthropic,
|
||||
model: 'claude-haiku-4-5-20251001',
|
||||
timeout: 120,
|
||||
);
|
||||
|
||||
// Streaming (returns SSE response from a route)
|
||||
return (new SalesCoach)->stream('Analyze this transcript...');
|
||||
|
||||
// Queueing
|
||||
(new SalesCoach)->queue('Analyze this transcript...')
|
||||
->then(fn ($response) => /* ... */);
|
||||
|
||||
// Anonymous agents
|
||||
use function Laravel\Ai\{agent};
|
||||
|
||||
$response = agent(instructions: 'You are a helpful assistant.')->prompt('Hello');
|
||||
```
|
||||
|
||||
### Conversation Context
|
||||
|
||||
Manual conversation history via the `Conversational` interface:
|
||||
|
||||
```php
|
||||
use Laravel\Ai\Contracts\Agent;
|
||||
use Laravel\Ai\Contracts\Conversational;
|
||||
use Laravel\Ai\Messages\Message;
|
||||
use Laravel\Ai\Promptable;
|
||||
|
||||
class SalesCoach implements Agent, Conversational
|
||||
{
|
||||
use Promptable;
|
||||
|
||||
public function __construct(public User $user) {}
|
||||
|
||||
public function instructions(): string { return 'You are a sales coach.'; }
|
||||
|
||||
public function messages(): iterable
|
||||
{
|
||||
return History::where('user_id', $this->user->id)
|
||||
->latest()->limit(50)->get()->reverse()
|
||||
->map(fn ($m) => new Message($m->role, $m->content))
|
||||
->all();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Automatic conversation persistence via the `RemembersConversations` trait:
|
||||
|
||||
```php
|
||||
use Laravel\Ai\Concerns\RemembersConversations;
|
||||
use Laravel\Ai\Contracts\Agent;
|
||||
use Laravel\Ai\Contracts\Conversational;
|
||||
use Laravel\Ai\Promptable;
|
||||
|
||||
class SalesCoach implements Agent, Conversational
|
||||
{
|
||||
use Promptable, RemembersConversations;
|
||||
|
||||
public function instructions(): string { return 'You are a sales coach.'; }
|
||||
}
|
||||
|
||||
// Start a new conversation
|
||||
$response = (new SalesCoach)->forUser($user)->prompt('Hello!');
|
||||
$conversationId = $response->conversationId;
|
||||
|
||||
// Continue an existing conversation
|
||||
$response = (new SalesCoach)->continue($conversationId, as: $user)->prompt('Tell me more.');
|
||||
```
|
||||
|
||||
### Structured Output
|
||||
|
||||
```php
|
||||
use Illuminate\Contracts\JsonSchema\JsonSchema;
|
||||
use Laravel\Ai\Contracts\Agent;
|
||||
use Laravel\Ai\Contracts\HasStructuredOutput;
|
||||
use Laravel\Ai\Promptable;
|
||||
|
||||
class Reviewer implements Agent, HasStructuredOutput
|
||||
{
|
||||
use Promptable;
|
||||
|
||||
public function instructions(): string { return 'Review and score content.'; }
|
||||
|
||||
public function schema(JsonSchema $schema): array
|
||||
{
|
||||
return [
|
||||
'feedback' => $schema->string()->required(),
|
||||
'score' => $schema->integer()->min(1)->max(10)->required(),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
$response = (new Reviewer)->prompt('Review this...');
|
||||
echo $response['score']; // Access like an array
|
||||
```
|
||||
|
||||
### Images
|
||||
|
||||
```php
|
||||
use Laravel\Ai\Image;
|
||||
|
||||
$image = Image::of('A sunset over mountains')
|
||||
->landscape()
|
||||
->quality('high')
|
||||
->generate();
|
||||
|
||||
$path = $image->store(); // Store to default disk
|
||||
```
|
||||
|
||||
### Audio
|
||||
|
||||
```php
|
||||
use Laravel\Ai\Audio;
|
||||
|
||||
$audio = Audio::of('Hello from Laravel.')
|
||||
->female()
|
||||
->instructions('Speak warmly')
|
||||
->generate();
|
||||
|
||||
$path = $audio->store();
|
||||
```
|
||||
|
||||
### Transcription
|
||||
|
||||
```php
|
||||
use Laravel\Ai\Transcription;
|
||||
|
||||
$transcript = Transcription::fromStorage('audio.mp3')
|
||||
->diarize()
|
||||
->generate();
|
||||
|
||||
echo (string) $transcript;
|
||||
```
|
||||
|
||||
### Embeddings
|
||||
|
||||
```php
|
||||
use Laravel\Ai\Embeddings;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
$response = Embeddings::for(['Text one', 'Text two'])
|
||||
->dimensions(1536)
|
||||
->cache()
|
||||
->generate();
|
||||
|
||||
// Single string via Stringable
|
||||
$embedding = Str::of('Napa Valley has great wine.')->toEmbeddings();
|
||||
```
|
||||
|
||||
### Reranking
|
||||
|
||||
```php
|
||||
use Laravel\Ai\Reranking;
|
||||
|
||||
$response = Reranking::of(['Django is Python.', 'Laravel is PHP.', 'React is JS.'])
|
||||
->limit(5)
|
||||
->rerank('PHP frameworks');
|
||||
|
||||
$response->first()->document; // "Laravel is PHP."
|
||||
```
|
||||
|
||||
### Files and Vector Stores
|
||||
|
||||
```php
|
||||
use Laravel\Ai\Files\Document;
|
||||
use Laravel\Ai\Stores;
|
||||
|
||||
// Store a file with the provider
|
||||
$file = Document::fromPath('/path/to/doc.pdf')->put();
|
||||
|
||||
// Create a vector store and add files
|
||||
$store = Stores::create('Knowledge Base');
|
||||
$store->add($file->id);
|
||||
$store->add(Document::fromStorage('manual.pdf')); // Store + add in one step
|
||||
```
|
||||
|
||||
## Agent Configuration
|
||||
|
||||
### PHP Attributes
|
||||
|
||||
```php
|
||||
use Laravel\Ai\Attributes\{Provider, Model, MaxSteps, MaxTokens, Temperature, Timeout};
|
||||
use Laravel\Ai\Enums\Lab;
|
||||
|
||||
#[Provider(Lab::Anthropic)]
|
||||
#[Model('claude-haiku-4-5-20251001')]
|
||||
#[MaxSteps(10)]
|
||||
#[MaxTokens(4096)]
|
||||
#[Temperature(0.7)]
|
||||
#[Timeout(120)]
|
||||
class MyAgent implements Agent
|
||||
{
|
||||
use Promptable;
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
The `#[UseCheapestModel]` and `#[UseSmartestModel]` attributes are also available for automatic model selection.
|
||||
|
||||
The `#[WithoutBroadcasting]` attribute stops the given stream event types from broadcasting (e.g. data-heavy `ToolResult` payloads that exceed the WebSocket frame limit). The events are still streamed and persisted; they just never hit the channel:
|
||||
|
||||
```php
|
||||
use Laravel\Ai\Attributes\WithoutBroadcasting;
|
||||
use Laravel\Ai\Streaming\Events\{ToolCall, ToolResult};
|
||||
|
||||
#[WithoutBroadcasting(ToolResult::class, ToolCall::class)]
|
||||
class SearchAgent implements Agent, HasTools
|
||||
{
|
||||
use Promptable;
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
### Tools
|
||||
|
||||
Implement the `HasTools` interface and scaffold tools with `php artisan make:tool`:
|
||||
|
||||
```php
|
||||
use Laravel\Ai\Contracts\HasTools;
|
||||
|
||||
class MyAgent implements Agent, HasTools
|
||||
{
|
||||
use Promptable;
|
||||
|
||||
public function tools(): iterable
|
||||
{
|
||||
return [new MyCustomTool];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Provider Tools
|
||||
|
||||
```php
|
||||
use Laravel\Ai\Providers\Tools\{WebSearch, WebFetch, FileSearch};
|
||||
|
||||
public function tools(): iterable
|
||||
{
|
||||
return [
|
||||
(new WebSearch)->max(5)->allow(['laravel.com']),
|
||||
new WebFetch,
|
||||
new FileSearch(stores: ['store_id']),
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
### Conversation Memory
|
||||
|
||||
```php
|
||||
use Laravel\Ai\Concerns\RemembersConversations;
|
||||
use Laravel\Ai\Contracts\Conversational;
|
||||
|
||||
class ChatBot implements Agent, Conversational
|
||||
{
|
||||
use Promptable, RemembersConversations;
|
||||
// ...
|
||||
}
|
||||
|
||||
$response = (new ChatBot)->forUser($user)->prompt('Hello!');
|
||||
$response = (new ChatBot)->continue($conversationId, as: $user)->prompt('More...');
|
||||
```
|
||||
|
||||
### Failover
|
||||
|
||||
```php
|
||||
$response = (new MyAgent)->prompt('Hello', provider: [Lab::OpenAI, Lab::Anthropic]);
|
||||
```
|
||||
|
||||
## Testing and Faking
|
||||
|
||||
Each capability supports `fake()` with assertions:
|
||||
|
||||
```php
|
||||
use App\Ai\Agents\SalesCoach;
|
||||
use Laravel\Ai\{Image, Audio, Transcription, Embeddings, Reranking, Files, Stores};
|
||||
|
||||
// Agents
|
||||
SalesCoach::fake(['Response 1', 'Response 2']);
|
||||
SalesCoach::assertPrompted('query');
|
||||
SalesCoach::assertNotPrompted('query');
|
||||
SalesCoach::assertNeverPrompted();
|
||||
SalesCoach::fake()->preventStrayPrompts();
|
||||
|
||||
// Images
|
||||
Image::fake();
|
||||
Image::assertGenerated(fn ($prompt) => $prompt->contains('sunset'));
|
||||
Image::assertNothingGenerated();
|
||||
|
||||
// Audio
|
||||
Audio::fake();
|
||||
Audio::assertGenerated(fn ($prompt) => $prompt->contains('Hello'));
|
||||
|
||||
// Transcription
|
||||
Transcription::fake(['Transcribed text.']);
|
||||
Transcription::assertGenerated(fn ($prompt) => $prompt->isDiarized());
|
||||
|
||||
// Embeddings
|
||||
Embeddings::fake();
|
||||
Embeddings::assertGenerated(fn ($prompt) => $prompt->contains('Laravel'));
|
||||
|
||||
// Reranking
|
||||
Reranking::fake();
|
||||
Reranking::assertReranked(fn ($prompt) => $prompt->contains('PHP'));
|
||||
|
||||
// Files
|
||||
Files::fake();
|
||||
Files::assertStored(fn ($file) => $file->mimeType() === 'text/plain');
|
||||
|
||||
// Stores
|
||||
Stores::fake();
|
||||
Stores::assertCreated('Knowledge Base');
|
||||
$store = Stores::get('id');
|
||||
$store->assertAdded('file_id');
|
||||
```
|
||||
|
||||
## Key Patterns
|
||||
|
||||
- Namespace: `Laravel\Ai\`
|
||||
- Package: `composer require laravel/ai`
|
||||
- Agent pattern: Implement the `Agent` interface and use the `Promptable` trait
|
||||
- Optional interfaces: `HasTools`, `HasMiddleware`, `HasStructuredOutput`, `Conversational`
|
||||
- Entry-point classes: `Image`, `Audio`, `Transcription`, `Embeddings`, `Reranking`, `Stores`
|
||||
- Provider enum: `Laravel\Ai\Enums\Lab` (prefer over plain strings)
|
||||
- Artisan commands: `php artisan make:agent`, `php artisan make:tool`
|
||||
- Global helper: `agent()` for anonymous agents
|
||||
|
||||
## OpenAI-Compatible Provider
|
||||
|
||||
Point the SDK at any OpenAI-compatible endpoint (LM Studio, vLLM, Together, etc.) with the config-driven `openai-compatible` driver. Define named instances in `config/ai.php`, no code required:
|
||||
|
||||
```php
|
||||
'my-llm' => [
|
||||
'driver' => 'openai-compatible',
|
||||
'url' => env('MY_LLM_URL'), // required
|
||||
'key' => env('MY_LLM_API_KEY'), // optional Bearer token
|
||||
'models' => [
|
||||
'text' => ['default' => 'some-chat-model'],
|
||||
'embeddings' => [
|
||||
'default' => 'some-embedding-model',
|
||||
'dimensions' => 1024, // optional; omit to use native dimensions
|
||||
],
|
||||
],
|
||||
],
|
||||
```
|
||||
|
||||
Reference it by config key (or `Lab::OpenAiCompatible`). A model is required via the corresponding `models` configuration or per-call `model:`:
|
||||
|
||||
```php
|
||||
agent()->prompt('Hello', provider: 'my-llm', model: 'some-model');
|
||||
|
||||
Embeddings::for(['Hello'])->generate(
|
||||
provider: 'my-llm',
|
||||
model: 'some-embedding-model',
|
||||
);
|
||||
```
|
||||
|
||||
It uses OpenAI-standard shapes and supports text, streaming, tools, structured output, image attachments, and text embeddings. Embedding dimensions are optional; omit them to use the model's native dimensions. For extra request-body fields, implement `HasProviderOptions` — the returned array is merged into the body.
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
### Wrong Namespace
|
||||
|
||||
The namespace is `Laravel\Ai`, not `Illuminate\Ai` or `Laravel\AI`.
|
||||
|
||||
```php
|
||||
// Correct
|
||||
use Laravel\Ai\Image;
|
||||
use Laravel\Ai\Contracts\Agent;
|
||||
use Laravel\Ai\Promptable;
|
||||
|
||||
// Wrong — these do not exist
|
||||
use Illuminate\Ai\Image;
|
||||
use Laravel\AI\Agent;
|
||||
```
|
||||
|
||||
### Unsupported Provider Capability
|
||||
|
||||
Calling a capability not supported by a provider throws a `LogicException`. Refer to the provider support table below.
|
||||
|
||||
## Provider Support
|
||||
|
||||
| Feature | Providers |
|
||||
| ---------- | --------------------------------------------------------------- |
|
||||
| Text | OpenAI, Anthropic, Gemini, Azure, Groq, xAI, DeepSeek, Mistral, Ollama, OpenRouter, OpenAI-compatible |
|
||||
| Images | OpenAI, Gemini, xAI |
|
||||
| TTS | OpenAI, ElevenLabs |
|
||||
| STT | OpenAI, ElevenLabs, Mistral |
|
||||
| Embeddings | OpenAI, OpenAI-compatible, Gemini, Azure, Cohere, Mistral, Jina, VoyageAI |
|
||||
| Reranking | Cohere, Jina |
|
||||
| Files | OpenAI, Anthropic, Gemini |
|
||||
|
||||
Use the `Laravel\Ai\Enums\Lab` enum to reference providers in code instead of plain strings:
|
||||
|
||||
```php
|
||||
use Laravel\Ai\Enums\Lab;
|
||||
|
||||
Lab::Anthropic;
|
||||
Lab::OpenAI;
|
||||
Lab::Gemini;
|
||||
Lab::OpenAiCompatible; // configurable OpenAI-compatible endpoint
|
||||
// ...
|
||||
```
|
||||
|
|
@ -1,98 +0,0 @@
|
|||
---
|
||||
name: cashier-stripe-development
|
||||
description: "Handles Laravel Cashier Stripe integration including subscriptions, webhooks, Stripe Checkout, invoices, charges, refunds, trials, coupons, metered billing, and payment failure handling. Triggered when a user mentions Cashier, Billable, IncompletePayment, stripe_id, newSubscription, Stripe subscriptions, or billing. Also applies when setting up webhooks, handling SCA/3DS payment failures, testing with Stripe test cards, or troubleshooting incomplete subscriptions, CSRF webhook errors, or migration publish issues."
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
|
||||
# Cashier Stripe Development
|
||||
|
||||
## Documentation
|
||||
|
||||
Use `search-docs` for detailed Cashier patterns and documentation covering subscriptions, webhooks, Stripe Checkout, invoices, payment methods, and testing.
|
||||
|
||||
For deeper guidance on specific topics, read the relevant reference file before implementing:
|
||||
|
||||
- `references/subscriptions.md` covers subscription creation, status checks, swapping, trials, quantities, and multiple products
|
||||
- `references/webhooks.md` covers webhook setup, custom handlers, CSRF exclusion, and local development with the Stripe CLI
|
||||
- `references/testing.md` covers Stripe test cards, payment method tokens, and feature test patterns
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
php artisan vendor:publish --tag="cashier-migrations"
|
||||
php artisan migrate
|
||||
php artisan vendor:publish --tag="cashier-config"
|
||||
```
|
||||
|
||||
### Environment Variables
|
||||
|
||||
```
|
||||
STRIPE_KEY=pk_test_...
|
||||
STRIPE_SECRET=sk_test_...
|
||||
STRIPE_WEBHOOK_SECRET=whsec_...
|
||||
CASHIER_CURRENCY=usd
|
||||
CASHIER_CURRENCY_LOCALE=en_US
|
||||
```
|
||||
|
||||
### Billable Model
|
||||
|
||||
<!-- Add Billable Trait -->
|
||||
```php
|
||||
use Laravel\Cashier\Billable;
|
||||
|
||||
class User extends Authenticatable
|
||||
{
|
||||
use Billable;
|
||||
}
|
||||
```
|
||||
|
||||
For a non-User model, register it in a service provider:
|
||||
|
||||
<!-- Custom Billable Model -->
|
||||
```php
|
||||
// In AppServiceProvider::boot()
|
||||
Cashier::useCustomerModel(Team::class);
|
||||
```
|
||||
|
||||
### Creating a Subscription
|
||||
|
||||
<!-- Create Subscription -->
|
||||
```php
|
||||
use Laravel\Cashier\Exceptions\IncompletePayment;
|
||||
|
||||
try {
|
||||
$user->newSubscription('default', 'price_xxxx')->create($paymentMethodId);
|
||||
} catch (IncompletePayment $e) {
|
||||
return redirect()->route('cashier.payment', [$e->payment->id, 'redirect' => route('home')]);
|
||||
}
|
||||
```
|
||||
|
||||
Always wrap subscription creation in a try/catch for `IncompletePayment`. When a card requires 3DS authentication, Cashier throws this exception. The `cashier.payment` route is auto-registered and handles the confirmation flow.
|
||||
|
||||
## Verification
|
||||
|
||||
1. Run migrations and confirm `stripe_id`, `pm_type`, `pm_last_four`, and `trial_ends_at` columns exist on the billable model table
|
||||
2. Test the webhook endpoint with `stripe listen --forward-to localhost/stripe/webhook` if you use the default path, or swap `stripe` for your configured `CASHIER_PATH`
|
||||
3. Confirm `$user->subscribed('default')` returns the expected value for active and incomplete subscriptions
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
- The migration publish tag is `cashier-migrations`, not `cashier`. Running `migrate` before publishing results in missing columns and tables.
|
||||
- `CASHIER_CURRENCY` must be set explicitly. It defaults to USD, which silently breaks non-US apps.
|
||||
- The Stripe CLI generates its own webhook signing secret. It is different from the Dashboard endpoint secret. Using the wrong one causes signature verification failures.
|
||||
- The webhook route must be excluded from CSRF verification using your configured `cashier.path`. If you change `CASHIER_PATH` from `stripe` to `billing`, exclude `billing/*`, not `stripe/*`.
|
||||
- `canceled()` returns true as soon as `cancel()` is called, but the user still has access during the grace period. Use `ended()` to confirm access is fully revoked.
|
||||
- `subscribed()` returns true during the grace period even though the subscription is canceled.
|
||||
- `subscribed()` returns false for `incomplete` and `past_due` subscriptions by default.
|
||||
- Prices cannot be swapped and quantity cannot be updated while a subscription has an incomplete payment.
|
||||
- When extending `WebhookController`, call `Cashier::ignoreRoutes()` in a service provider and re-register both `cashier.payment` and `cashier.webhook` under the configured `cashier.path`.
|
||||
- Use `Cashier::useCustomerModel()` in a service provider to set a custom billable model. There is no `CASHIER_MODEL` env var.
|
||||
- `trial_ends_at` is a local database column synced via webhooks. It will be stale if webhooks are not configured in production.
|
||||
- In MySQL, the `stripe_id` column must use `utf8_bin` collation to avoid case-sensitivity issues.
|
||||
- `noProrate()` has no effect when combined with `swapAndInvoice()`. That method always prorates.
|
||||
- Methods like `withPromotionCode()` require the Stripe API ID such as `promo_xxxx`, not the customer-facing code. Use `findPromotionCode()` to resolve a code to its ID.
|
||||
- Always use `search-docs` for the latest Cashier documentation rather than relying on this skill alone.
|
||||
|
|
@ -1,108 +0,0 @@
|
|||
# Subscriptions Reference
|
||||
|
||||
Use `search-docs` for authoritative documentation on subscriptions.
|
||||
|
||||
## Status Checks
|
||||
|
||||
| Method | Returns true when |
|
||||
|---|---|
|
||||
| `$user->subscribed('default')` | Active or on grace period |
|
||||
| `->onTrial()` | Trial period active |
|
||||
| `->onGracePeriod()` | Canceled, period not yet ended |
|
||||
| `->canceled()` | `ends_at` is set, may still have access |
|
||||
| `->ended()` | Canceled and grace period expired |
|
||||
| `->incomplete()` | Awaiting SCA/3DS confirmation |
|
||||
| `->pastDue()` | Payment overdue |
|
||||
| `->recurring()` | Active and not on trial |
|
||||
|
||||
Check by product or price:
|
||||
|
||||
```php
|
||||
$user->subscribedToProduct('prod_premium', 'default');
|
||||
$user->subscribedToPrice('price_monthly', 'default');
|
||||
```
|
||||
|
||||
## Swapping Plans
|
||||
|
||||
```php
|
||||
$user->subscription('default')->swap('price_new');
|
||||
$user->subscription('default')->noProrate()->swap('price_new');
|
||||
$user->subscription('default')->swapAndInvoice('price_new');
|
||||
$user->subscription('default')->skipTrial()->swap('price_new');
|
||||
```
|
||||
|
||||
## Quantity
|
||||
|
||||
```php
|
||||
$user->subscription('default')->incrementQuantity();
|
||||
$user->subscription('default')->decrementQuantity();
|
||||
$user->subscription('default')->updateQuantity(10);
|
||||
$user->subscription('default')->noProrate()->updateQuantity(10);
|
||||
```
|
||||
|
||||
## Trials
|
||||
|
||||
```php
|
||||
$user->newSubscription('default', 'price_xxxx')
|
||||
->trialDays(14)
|
||||
->create($paymentMethodId);
|
||||
|
||||
$subscription->extendTrial(now()->addDays(7));
|
||||
```
|
||||
|
||||
## Multiple Products on One Subscription
|
||||
|
||||
```php
|
||||
$user->newSubscription('default', ['price_monthly', 'price_chat'])
|
||||
->quantity(5, 'price_chat')
|
||||
->create($paymentMethod);
|
||||
|
||||
$user->subscription('default')->addPrice('price_chat');
|
||||
$user->subscription('default')->removePrice('price_chat');
|
||||
$user->subscription('default')->swap(['price_pro', 'price_chat']);
|
||||
```
|
||||
|
||||
## Multiple Subscriptions
|
||||
|
||||
```php
|
||||
$user->newSubscription('swimming', 'price_swimming_monthly')->create($pm);
|
||||
$user->newSubscription('gym', 'price_gym_monthly')->create($pm);
|
||||
|
||||
$user->subscription('swimming')->swap('price_swimming_yearly');
|
||||
$user->subscription('gym')->cancel();
|
||||
```
|
||||
|
||||
## Cancellation and Resumption
|
||||
|
||||
```php
|
||||
$user->subscription('default')->cancel(); // At end of billing period
|
||||
$user->subscription('default')->cancelNow(); // Immediately
|
||||
$user->subscription('default')->resume(); // During grace period only
|
||||
```
|
||||
|
||||
## Incomplete Payment Handling
|
||||
|
||||
```php
|
||||
if ($user->hasIncompletePayment('default')) {
|
||||
$paymentId = $user->subscription('default')->latestPayment()->id;
|
||||
return redirect()->route('cashier.payment', $paymentId);
|
||||
}
|
||||
```
|
||||
|
||||
Opt out of default deactivation behavior:
|
||||
|
||||
```php
|
||||
Cashier::keepPastDueSubscriptionsActive();
|
||||
Cashier::keepIncompleteSubscriptionsActive();
|
||||
```
|
||||
|
||||
## Metered / Usage-Based Billing
|
||||
|
||||
```php
|
||||
$user->newSubscription('default')
|
||||
->meteredPrice('price_metered')
|
||||
->create($paymentMethodId);
|
||||
|
||||
$user->reportMeterEvent('emails-sent');
|
||||
$user->reportMeterEvent('emails-sent', quantity: 15);
|
||||
```
|
||||
|
|
@ -1,52 +0,0 @@
|
|||
# Testing Reference
|
||||
|
||||
Use `search-docs` for authoritative documentation on testing Cashier integrations.
|
||||
|
||||
## Test Cards and Tokens
|
||||
|
||||
Use card numbers for browser-based flows (Stripe.js / Checkout). Use `pm_card_*` tokens directly in feature tests that call the Stripe API.
|
||||
|
||||
| Card Number | Token | Behavior |
|
||||
|---|---|---|
|
||||
| `4242 4242 4242 4242` | `pm_card_visa` | Succeeds immediately |
|
||||
| `4000 0025 0000 3155` | `pm_card_threeDSecure2Required` | Requires SCA/3DS |
|
||||
| `4000 0027 6000 3184` | `pm_card_authenticationRequired` | Requires authentication |
|
||||
| `4000 0000 0000 9995` | `pm_card_chargeDeclinedInsufficientFunds` | Declined, insufficient funds |
|
||||
| `4000 0000 0000 0002` | `pm_card_chargeDeclined` | Declined |
|
||||
|
||||
Use expiry `12/34`, any CVC, any ZIP for card number inputs.
|
||||
|
||||
## Feature Test Example
|
||||
|
||||
Feature tests that hit the real Stripe test API use `pm_card_*` tokens:
|
||||
|
||||
```php
|
||||
public function test_user_can_subscribe(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$user->newSubscription('default', 'price_xxxx')
|
||||
->create('pm_card_visa');
|
||||
|
||||
$this->assertTrue($user->subscribed('default'));
|
||||
}
|
||||
|
||||
public function test_incomplete_payment_is_handled(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
try {
|
||||
$user->newSubscription('default', 'price_xxxx')
|
||||
->create('pm_card_threeDSecure2Required');
|
||||
} catch (\Laravel\Cashier\Exceptions\IncompletePayment $e) {
|
||||
$this->assertTrue($user->subscription('default')->incomplete());
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Setup Notes
|
||||
|
||||
- Use Stripe test mode keys (`sk_test_...`, `pk_test_...`) in your test environment
|
||||
- Cashier does not ship a global `fake()` helper. Tests hit the real Stripe test API by default.
|
||||
- Refer to `tests/Feature/` in the Cashier package itself for integration test patterns covering subscription creation, payment methods, and webhook handling
|
||||
- Use `search-docs` for current guidance on mocking Stripe HTTP calls or using Stripe's test clock feature for time-sensitive scenarios
|
||||
|
|
@ -1,132 +0,0 @@
|
|||
# Webhooks Reference
|
||||
|
||||
Use `search-docs` for authoritative documentation on webhooks.
|
||||
|
||||
## Auto-Registered Routes
|
||||
|
||||
Cashier registers two routes automatically under the `cashier.path` prefix (`config('cashier.path')`, default `stripe`):
|
||||
|
||||
- `POST /{cashier.path}/webhook` named `cashier.webhook`
|
||||
- `GET /{cashier.path}/payment/{id}` named `cashier.payment`
|
||||
|
||||
With the default config these are `/stripe/webhook` and `/stripe/payment/{id}`. If you set `CASHIER_PATH=billing`, they become `/billing/webhook` and `/billing/payment/{id}`.
|
||||
|
||||
## CSRF Exclusion
|
||||
|
||||
Use the same path prefix you configured for Cashier here. If `CASHIER_PATH=billing`, exclude `billing/*` instead of `stripe/*`.
|
||||
|
||||
**Laravel 11+ (`bootstrap/app.php`, default path example):**
|
||||
|
||||
```php
|
||||
->withMiddleware(function (Middleware $middleware) {
|
||||
$middleware->validateCsrfTokens(except: ['stripe/*']);
|
||||
})
|
||||
```
|
||||
|
||||
**Laravel 10 (`app/Http/Middleware/VerifyCsrfToken.php`, default path example):**
|
||||
|
||||
```php
|
||||
protected $except = [
|
||||
'stripe/*',
|
||||
];
|
||||
```
|
||||
|
||||
## Local Development with Stripe CLI
|
||||
|
||||
If you changed `cashier.path`, forward Stripe CLI events to that URL instead of `/stripe/webhook`.
|
||||
|
||||
```bash
|
||||
stripe login
|
||||
stripe listen --forward-to your-app.test/stripe/webhook
|
||||
stripe trigger invoice.payment_succeeded
|
||||
```
|
||||
|
||||
The CLI outputs a `whsec_...` signing secret specific to that session. Set it as `STRIPE_WEBHOOK_SECRET` locally. It is not the same as the Dashboard endpoint secret.
|
||||
|
||||
## Registering Events in the Stripe Dashboard
|
||||
|
||||
Use the Artisan command to create the endpoint automatically with all required events:
|
||||
|
||||
```bash
|
||||
php artisan cashier:webhook
|
||||
```
|
||||
|
||||
Cashier's `cashier:webhook` command registers these events by default:
|
||||
|
||||
- `customer.subscription.created`
|
||||
- `customer.subscription.updated`
|
||||
- `customer.subscription.deleted`
|
||||
- `customer.updated` / `customer.deleted`
|
||||
- `invoice.payment_action_required`
|
||||
- `invoice.payment_succeeded`
|
||||
- `payment_method.automatically_updated`
|
||||
|
||||
Cashier's `WebhookController` has built-in handlers for all of the above except `invoice.payment_succeeded`. For renewal hooks, prefer `WebhookReceived` / `WebhookHandled` listeners unless you intentionally add your own controller method.
|
||||
|
||||
## Custom Handlers: Extending WebhookController
|
||||
|
||||
Method name pattern: `handle` + StudlyCase of event type with dots replaced by underscores.
|
||||
|
||||
`customer.subscription.created` becomes `handleCustomerSubscriptionCreated`.
|
||||
|
||||
```php
|
||||
use Laravel\Cashier\Http\Controllers\WebhookController as CashierController;
|
||||
|
||||
class StripeWebhookController extends CashierController
|
||||
{
|
||||
public function handleCustomerSubscriptionCreated(array $payload)
|
||||
{
|
||||
$response = parent::handleCustomerSubscriptionCreated($payload);
|
||||
|
||||
// your logic after Cashier syncs the subscription
|
||||
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If you add a method for an event Cashier does not handle internally, such as `invoice.payment_succeeded`, do not call `parent::handle...()` unless the base controller actually defines that method.
|
||||
|
||||
In a service provider, disable auto-registration and re-register both Cashier routes so the incomplete-payment flow and `cashier:webhook` command keep working:
|
||||
|
||||
```php
|
||||
Cashier::ignoreRoutes();
|
||||
```
|
||||
|
||||
```php
|
||||
// routes/web.php
|
||||
use App\Http\Controllers\StripeWebhookController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Laravel\Cashier\Http\Controllers\PaymentController;
|
||||
|
||||
Route::prefix(config('cashier.path'))
|
||||
->name('cashier.')
|
||||
->group(function () {
|
||||
Route::get('payment/{id}', [PaymentController::class, 'show'])->name('payment');
|
||||
Route::post('webhook', [StripeWebhookController::class, 'handleWebhook'])->name('webhook');
|
||||
});
|
||||
```
|
||||
|
||||
Keep the `cashier.webhook` route name unless you plan to pass `--url` explicitly to `php artisan cashier:webhook`.
|
||||
|
||||
## Custom Handlers: Listening to Events
|
||||
|
||||
The simpler option when you do not need to replace Cashier's internal logic, or when you want to react to events such as `invoice.payment_succeeded` that Cashier does not process itself:
|
||||
|
||||
```php
|
||||
use Laravel\Cashier\Events\WebhookReceived;
|
||||
use Laravel\Cashier\Events\WebhookHandled;
|
||||
|
||||
// WebhookReceived fires for every event before Cashier processes it
|
||||
// WebhookHandled fires after Cashier processes it
|
||||
|
||||
Event::listen(WebhookReceived::class, function (WebhookReceived $event) {
|
||||
if ($event->payload['type'] === 'invoice.payment_succeeded') {
|
||||
// handle renewal
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## Signature Verification
|
||||
|
||||
`VerifyWebhookSignature` middleware is applied automatically when `cashier.webhook.secret` is set. No extra wiring is needed.
|
||||
|
|
@ -1,404 +0,0 @@
|
|||
---
|
||||
name: configure-nightwatch
|
||||
description: Configures Laravel Nightwatch data collection, sampling rates, filtering rules, and redaction policies. Use when setting up Nightwatch, managing data volume, protecting sensitive data (PII), or optimizing event collection for production workloads.
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
|
||||
# Nightwatch Configuration Guide
|
||||
|
||||
This skill helps configure Laravel Nightwatch data collection to balance observability, performance, and privacy. Covers sampling strategies, filtering rules, and redaction methods across all event types.
|
||||
|
||||
## Documentation Reference
|
||||
|
||||
The [Nightwatch Documentation](https://nightwatch.laravel.com/docs) is the definitive and up-to-date source of information for all Nightwatch configuration options. This skill provides practical guidance and common patterns, but always consult the official documentation as the primary source of truth for specific details, environment variables, and API behavior. The documentation includes comprehensive coverage of:
|
||||
|
||||
- [Filtering and Configuration](https://nightwatch.laravel.com/docs/filtering) - Core concepts for sampling, filtering, and redaction
|
||||
- Individual event type pages with specific configuration options:
|
||||
- [Requests](https://nightwatch.laravel.com/docs/requests) - Request sampling, header handling, payload capture
|
||||
- [Commands](https://nightwatch.laravel.com/docs/commands) - Command sampling and redaction
|
||||
- [Queries](https://nightwatch.laravel.com/docs/queries) - Query filtering and redaction
|
||||
- [Cache](https://nightwatch.laravel.com/docs/cache) - Cache event filtering by key or pattern
|
||||
- [Jobs](https://nightwatch.laravel.com/docs/jobs) - Job filtering and sampling decoupling
|
||||
- [Mail](https://nightwatch.laravel.com/docs/mail) - Mail event filtering
|
||||
- [Notifications](https://nightwatch.laravel.com/docs/notifications) - Notification filtering by channel
|
||||
- [Exceptions](https://nightwatch.laravel.com/docs/exceptions) - Exception sampling and throttling
|
||||
- [Outgoing Requests](https://nightwatch.laravel.com/docs/outgoing-requests) - HTTP request filtering
|
||||
- [reference.md](reference.md) - Quick lookup table by event type, production presets, and verification checklist
|
||||
|
||||
## Data Collection Flow
|
||||
|
||||
Nightwatch processes events through three stages:
|
||||
|
||||
1. **Sampling** - Controls which entry points are captured (requests, commands, scheduled tasks)
|
||||
2. **Filtering** - Excludes specific events after sampling (queries, cache, mail, etc.)
|
||||
3. **Redaction** - Modifies captured data to remove/obfuscate sensitive information
|
||||
|
||||
```
|
||||
Request/Command/Scheduled Task
|
||||
|
|
||||
v
|
||||
[Sampling?] ----NO----> Drop entire trace
|
||||
| YES
|
||||
v
|
||||
Events generated
|
||||
|
|
||||
v
|
||||
[Filtering?] ----YES---> Drop specific event
|
||||
| NO
|
||||
v
|
||||
[Redaction] ----------> Store modified data
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Sampling Configuration
|
||||
|
||||
Sampling determines which entry points (requests, commands, scheduled tasks) trigger full trace collection. When an entry point is sampled, all related events are captured.
|
||||
|
||||
### Global Sample Rates
|
||||
|
||||
Configure via environment variables:
|
||||
|
||||
```bash
|
||||
|
||||
# Default: 100% sampling (all requests/commands captured)
|
||||
|
||||
NIGHTWATCH_REQUEST_SAMPLE_RATE=0.1 # Recommended: 10% of requests
|
||||
|
||||
NIGHTWATCH_COMMAND_SAMPLE_RATE=1.0 # Capture all commands
|
||||
|
||||
NIGHTWATCH_EXCEPTION_SAMPLE_RATE=1.0 # Always capture exceptions
|
||||
|
||||
```
|
||||
|
||||
**Recommendation**: Start with `0.1` (10%) for requests in production, adjust based on volume and needs.
|
||||
|
||||
### Route-Based Sampling
|
||||
|
||||
Apply different rates to specific routes using the `Sample` middleware:
|
||||
|
||||
```php routes/web.php
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Laravel\Nightwatch\Http\Middleware\Sample;
|
||||
|
||||
// Sample admin routes at 100%
|
||||
Route::middleware(Sample::rate(1.0))->prefix('admin')->group(function () {
|
||||
// All admin routes sampled fully
|
||||
});
|
||||
|
||||
// Sample API routes at 5%
|
||||
Route::middleware(Sample::rate(0.05))->prefix('api')->group(function () {
|
||||
// API routes sampled sparingly
|
||||
});
|
||||
|
||||
// Always sample critical endpoints
|
||||
Route::post('/checkout', [CheckoutController::class, 'process'])
|
||||
->middleware(Sample::always());
|
||||
|
||||
// Never sample health checks
|
||||
Route::get('/health', [HealthController::class, 'check'])
|
||||
->middleware(Sample::never());
|
||||
```
|
||||
|
||||
### Unmatched Route Sampling
|
||||
|
||||
Handle 404/bot traffic with reduced sampling:
|
||||
|
||||
```php routes/web.php
|
||||
Route::fallback(fn () => abort(404))
|
||||
->middleware(Sample::rate(0.01)); // 1% sampling for unmatched routes
|
||||
```
|
||||
|
||||
### Dynamic Sampling
|
||||
|
||||
Sample based on runtime conditions (user role, request attributes):
|
||||
|
||||
```php app/Http/Middleware/SampleAdminRequests.php
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Laravel\Nightwatch\Facades\Nightwatch;
|
||||
|
||||
class SampleAdminRequests
|
||||
{
|
||||
public function handle(Request $request, Closure $next)
|
||||
{
|
||||
if ($request->user()?->isAdmin()) {
|
||||
Nightwatch::sample(); // Always sample admin requests
|
||||
}
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Command Sampling
|
||||
|
||||
Exclude specific commands from sampling:
|
||||
|
||||
```php AppServiceProvider.php
|
||||
use Illuminate\Console\Events\CommandStarting;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Laravel\Nightwatch\Facades\Nightwatch;
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
Event::listen(function (CommandStarting $event) {
|
||||
if (in_array($event->command, ['schedule:finish', 'horizon:snapshot'])) {
|
||||
Nightwatch::dontSample();
|
||||
}
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### Vendor Commands
|
||||
|
||||
Nightwatch automatically ignores framework/internal commands. Opt-in to capture them:
|
||||
|
||||
```php
|
||||
Nightwatch::captureDefaultVendorCommands();
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Filtering Configuration
|
||||
|
||||
Filtering excludes specific events from collection after sampling. Use filtering to reduce noise and quota usage.
|
||||
|
||||
### Database Queries
|
||||
|
||||
**Filter all queries** (disable query collection):
|
||||
|
||||
```bash
|
||||
NIGHTWATCH_IGNORE_QUERIES=true
|
||||
```
|
||||
|
||||
**Filter specific queries** by SQL pattern:
|
||||
|
||||
```php AppServiceProvider.php
|
||||
use Laravel\Nightwatch\Facades\Nightwatch;
|
||||
use Laravel\Nightwatch\Records\Query;
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
// Filter job table queries (PostgreSQL)
|
||||
Nightwatch::rejectQueries(function (Query $query) {
|
||||
return str_contains($query->sql, 'into "jobs"');
|
||||
});
|
||||
|
||||
// Filter cache table queries (MySQL)
|
||||
Nightwatch::rejectQueries(function (Query $query) {
|
||||
return str_contains($query->sql, 'from `cache`')
|
||||
|| str_contains($query->sql, 'into `cache`');
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### Cache Events
|
||||
|
||||
**Filter all cache events**:
|
||||
|
||||
```bash
|
||||
NIGHTWATCH_IGNORE_CACHE_EVENTS=true
|
||||
```
|
||||
|
||||
**Filter by cache key patterns**:
|
||||
|
||||
```php
|
||||
Nightwatch::rejectCacheKeys([
|
||||
'my-app:users', // Exact match
|
||||
'/^my-app:posts:/', // Regex: starts with my-app:posts:
|
||||
'/^[a-zA-Z0-9]{40}$/', // Regex: session IDs
|
||||
]);
|
||||
```
|
||||
|
||||
**Filter with callback**:
|
||||
|
||||
```php
|
||||
use Laravel\Nightwatch\Records\CacheEvent;
|
||||
|
||||
Nightwatch::rejectCacheEvents(function (CacheEvent $cacheEvent) {
|
||||
return str_starts_with($cacheEvent->key, 'temp:');
|
||||
});
|
||||
```
|
||||
|
||||
### Mail Events
|
||||
|
||||
**Filter all mail**:
|
||||
|
||||
```bash
|
||||
NIGHTWATCH_IGNORE_MAIL=true
|
||||
```
|
||||
|
||||
**Filter specific mail**:
|
||||
|
||||
```php
|
||||
use Laravel\Nightwatch\Records\Mail;
|
||||
|
||||
Nightwatch::rejectMail(function (Mail $mail) {
|
||||
return str_contains($mail->subject, 'Newsletter');
|
||||
});
|
||||
```
|
||||
|
||||
### Notification Events
|
||||
|
||||
**Filter all notifications**:
|
||||
|
||||
```bash
|
||||
NIGHTWATCH_IGNORE_NOTIFICATIONS=true
|
||||
```
|
||||
|
||||
**Filter by channel**:
|
||||
|
||||
```php
|
||||
use Laravel\Nightwatch\Records\Notification;
|
||||
|
||||
Nightwatch::rejectNotifications(function (Notification $notification) {
|
||||
return $notification->channel === 'database';
|
||||
});
|
||||
```
|
||||
|
||||
### Outgoing HTTP Requests
|
||||
|
||||
**Filter all outgoing requests**:
|
||||
|
||||
```bash
|
||||
NIGHTWATCH_IGNORE_OUTGOING_REQUESTS=true
|
||||
```
|
||||
|
||||
**Filter by URL**:
|
||||
|
||||
```php
|
||||
use Laravel\Nightwatch\Records\OutgoingRequest;
|
||||
|
||||
Nightwatch::rejectOutgoingRequests(function (OutgoingRequest $request) {
|
||||
return str_contains($request->url, 'analytics.example.com');
|
||||
});
|
||||
```
|
||||
|
||||
### Queued Jobs
|
||||
|
||||
**Filter specific jobs**:
|
||||
|
||||
```php
|
||||
use Laravel\Nightwatch\Records\QueuedJob;
|
||||
|
||||
Nightwatch::rejectQueuedJobs(function (QueuedJob $job) {
|
||||
return $job->name === 'App\Jobs\LowPriorityJob';
|
||||
});
|
||||
```
|
||||
|
||||
### Decoupling Job Sampling
|
||||
|
||||
Sample jobs independently from parent contexts:
|
||||
|
||||
```php
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
Queue::before(fn () => Nightwatch::sample(rate: 0.5));
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Redaction Configuration
|
||||
|
||||
Redaction modifies captured data to remove or obfuscate sensitive information. Unlike filtering, redaction keeps the event but sanitizes its content.
|
||||
|
||||
### Request Redaction
|
||||
|
||||
**Redact sensitive headers** (automatically redacts: Authorization, Cookie, X-XSRF-TOKEN):
|
||||
|
||||
```bash
|
||||
|
||||
# Customize redacted headers
|
||||
|
||||
NIGHTWATCH_REDACT_HEADERS=Authorization,Cookie,Proxy-Authorization,X-API-Key
|
||||
```
|
||||
|
||||
**Redact request payloads** (disabled by default):
|
||||
|
||||
```bash
|
||||
|
||||
# Enable payload capture
|
||||
|
||||
NIGHTWATCH_CAPTURE_REQUEST_PAYLOAD=true
|
||||
|
||||
# Customize redacted fields
|
||||
|
||||
NIGHTWATCH_REDACT_PAYLOAD_FIELDS=password,password_confirmation,ssn,credit_card
|
||||
```
|
||||
|
||||
**Programmatic redaction**:
|
||||
|
||||
```php
|
||||
use Laravel\Nightwatch\Facades\Nightwatch;
|
||||
use Laravel\Nightwatch\Records\Request;
|
||||
|
||||
Nightwatch::redactRequests(function (Request $request) {
|
||||
$request->url = str_replace('secret', '***', $request->url);
|
||||
$request->ip = preg_replace('/\d+$/', '***', $request->ip);
|
||||
});
|
||||
```
|
||||
|
||||
### Query Redaction
|
||||
|
||||
```php
|
||||
use Laravel\Nightwatch\Records\Query;
|
||||
|
||||
Nightwatch::redactQueries(function (Query $query) {
|
||||
$query->sql = str_replace('secret_token', '***', $query->sql);
|
||||
});
|
||||
```
|
||||
|
||||
### Cache Redaction
|
||||
|
||||
```php
|
||||
use Laravel\Nightwatch\Records\CacheEvent;
|
||||
|
||||
Nightwatch::redactCacheEvents(function (CacheEvent $cacheEvent) {
|
||||
$cacheEvent->key = str_replace('user:', 'user:***:', $cacheEvent->key);
|
||||
});
|
||||
```
|
||||
|
||||
### Command Redaction
|
||||
|
||||
```php
|
||||
use Laravel\Nightwatch\Records\Command;
|
||||
|
||||
Nightwatch::redactCommands(function (Command $command) {
|
||||
$command->command = preg_replace('/--password=\S+/', '--password=***', $command->command);
|
||||
});
|
||||
```
|
||||
|
||||
### Exception Redaction
|
||||
|
||||
```php
|
||||
use Laravel\Nightwatch\Records\Exception;
|
||||
|
||||
Nightwatch::redactExceptions(function (Exception $exception) {
|
||||
$exception->message = str_replace('secret', '***', $exception->message);
|
||||
});
|
||||
```
|
||||
|
||||
### Mail Redaction
|
||||
|
||||
```php
|
||||
use Laravel\Nightwatch\Records\Mail;
|
||||
|
||||
Nightwatch::redactMail(function (Mail $mail) {
|
||||
$mail->subject = str_replace('Invoice #', 'Invoice ***', $mail->subject);
|
||||
});
|
||||
```
|
||||
|
||||
### Outgoing Request Redaction
|
||||
|
||||
```php
|
||||
use Laravel\Nightwatch\Records\OutgoingRequest;
|
||||
|
||||
Nightwatch::redactOutgoingRequests(function (OutgoingRequest $outgoingRequest) {
|
||||
$outgoingRequest->url = preg_replace('/api_key=\w+/', 'api_key=***', $outgoingRequest->url);
|
||||
});
|
||||
```
|
||||
|
|
@ -1,108 +0,0 @@
|
|||
# Nightwatch Configuration Reference
|
||||
|
||||
## Configuration Summary by Event Type
|
||||
|
||||
| Event Type | Sampling | Filtering | Redaction |
|
||||
| --------------------- | -------------------------------------------------- | ---------------------------------------------------------------------------- | ------------------------- |
|
||||
| **Requests** | `NIGHTWATCH_REQUEST_SAMPLE_RATE`, Route middleware | Not applicable | Headers, payload, URL, IP |
|
||||
| **Commands** | `NIGHTWATCH_COMMAND_SAMPLE_RATE`, Event listener | Not applicable | Command arguments |
|
||||
| **Queries** | Parent context | `rejectQueries()`, `NIGHTWATCH_IGNORE_QUERIES` | SQL statement |
|
||||
| **Cache** | Parent context | `rejectCacheKeys()`, `rejectCacheEvents()`, `NIGHTWATCH_IGNORE_CACHE_EVENTS` | Cache key |
|
||||
| **Jobs** | Parent context, Queue::before | `rejectQueuedJobs()` | Not applicable |
|
||||
| **Mail** | Parent context | `rejectMail()`, `NIGHTWATCH_IGNORE_MAIL` | Subject |
|
||||
| **Notifications** | Parent context | `rejectNotifications()`, `NIGHTWATCH_IGNORE_NOTIFICATIONS` | Not applicable |
|
||||
| **Outgoing Requests** | Parent context | `rejectOutgoingRequests()`, `NIGHTWATCH_IGNORE_OUTGOING_REQUESTS` | URL |
|
||||
| **Exceptions** | `NIGHTWATCH_EXCEPTION_SAMPLE_RATE` | Not applicable | Exception message |
|
||||
|
||||
---
|
||||
|
||||
## Production Recommendations
|
||||
|
||||
### High-Traffic Applications
|
||||
|
||||
```bash
|
||||
|
||||
# Conservative sampling
|
||||
|
||||
NIGHTWATCH_REQUEST_SAMPLE_RATE=0.01 # 1% of requests
|
||||
|
||||
NIGHTWATCH_COMMAND_SAMPLE_RATE=0.1 # 10% of commands
|
||||
|
||||
NIGHTWATCH_EXCEPTION_SAMPLE_RATE=1.0 # Always capture exceptions
|
||||
|
||||
# Filter noisy events
|
||||
|
||||
NIGHTWATCH_IGNORE_CACHE_EVENTS=true
|
||||
NIGHTWATCH_IGNORE_QUERIES=true # Or filter specific queries programmatically
|
||||
|
||||
```
|
||||
|
||||
### Privacy-Conscious Applications
|
||||
|
||||
```bash
|
||||
|
||||
# Disable sensitive data collection
|
||||
|
||||
NIGHTWATCH_CAPTURE_REQUEST_PAYLOAD=false
|
||||
NIGHTWATCH_REDACT_HEADERS=Authorization,Cookie,Proxy-Authorization,X-XSRF-TOKEN
|
||||
|
||||
# Or use redaction in AppServiceProvider
|
||||
|
||||
```
|
||||
|
||||
### Balanced Configuration (Recommended Start)
|
||||
|
||||
```bash
|
||||
|
||||
# Sample rates
|
||||
|
||||
NIGHTWATCH_REQUEST_SAMPLE_RATE=0.1
|
||||
NIGHTWATCH_COMMAND_SAMPLE_RATE=1.0
|
||||
NIGHTWATCH_EXCEPTION_SAMPLE_RATE=1.0
|
||||
|
||||
# Filter obvious noise programmatically
|
||||
|
||||
# Redact PII as needed
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Verification Checklist
|
||||
|
||||
After configuration:
|
||||
|
||||
- [ ] Sampling rates appropriate for traffic volume
|
||||
- [ ] Noisy events filtered (cache, certain queries)
|
||||
- [ ] Sensitive data redacted (PII, tokens, credentials)
|
||||
- [ ] Exceptions always captured for debugging
|
||||
- [ ] Test in development with `NIGHTWATCH_REQUEST_SAMPLE_RATE=1.0`
|
||||
- [ ] Monitor event quota usage in Nightwatch dashboard
|
||||
|
||||
---
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Filter Health Checks + Reduce Sampling
|
||||
|
||||
```php
|
||||
Route::get('/health', fn() => ['status' => 'ok'])
|
||||
->middleware(Sample::never());
|
||||
```
|
||||
|
||||
### Exclude Internal/Vendor Queries
|
||||
|
||||
```php
|
||||
Nightwatch::rejectQueries(fn($q) =>
|
||||
str_contains($q->sql, 'telescope') ||
|
||||
str_contains($q->sql, 'pulse')
|
||||
);
|
||||
```
|
||||
|
||||
### Protect User Data in Cache Keys
|
||||
|
||||
```php
|
||||
Nightwatch::redactCacheEvents(fn($e) =>
|
||||
$e->key = preg_replace('/user:\d+/', 'user:***', $e->key)
|
||||
);
|
||||
```
|
||||
|
|
@ -1,85 +0,0 @@
|
|||
---
|
||||
name: configuring-horizon
|
||||
description: "Use this skill whenever the user mentions Horizon by name in a Laravel context. Covers the full Horizon lifecycle: installing Horizon (horizon:install, Sail setup), configuring config/horizon.php (supervisor blocks, queue assignments, balancing strategies, minProcesses/maxProcesses), fixing the dashboard (authorization via Gate::define viewHorizon, blank metrics, horizon:snapshot scheduling), and troubleshooting production issues (worker crashes, timeout chain ordering, LongWaitDetected notifications, waits config). Also covers job tagging and silencing. Do not use for generic Laravel queues without Horizon, SQS or database drivers, standalone Redis setup, Linux supervisord, Telescope, or job batching."
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
|
||||
# Horizon Configuration
|
||||
|
||||
## Documentation
|
||||
|
||||
Use `search-docs` for detailed Horizon patterns and documentation covering configuration, supervisors, balancing, dashboard authorization, tags, notifications, metrics, and deployment.
|
||||
|
||||
For deeper guidance on specific topics, read the relevant reference file before implementing:
|
||||
|
||||
- `references/supervisors.md` covers supervisor blocks, balancing strategies, multi-queue setups, and auto-scaling
|
||||
- `references/notifications.md` covers LongWaitDetected alerts, notification routing, and the `waits` config
|
||||
- `references/tags.md` covers job tagging, dashboard filtering, and silencing noisy jobs
|
||||
- `references/metrics.md` covers the blank metrics dashboard, snapshot scheduling, and retention config
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
php artisan horizon:install
|
||||
```
|
||||
|
||||
### Supervisor Configuration
|
||||
|
||||
Define supervisors in `config/horizon.php`. The `environments` array merges into `defaults` and does not replace the whole supervisor block:
|
||||
|
||||
<!-- Supervisor Config -->
|
||||
```php
|
||||
'defaults' => [
|
||||
'supervisor-1' => [
|
||||
'connection' => 'redis',
|
||||
'queue' => ['default'],
|
||||
'balance' => 'auto',
|
||||
'minProcesses' => 1,
|
||||
'maxProcesses' => 10,
|
||||
'tries' => 3,
|
||||
],
|
||||
],
|
||||
|
||||
'environments' => [
|
||||
'production' => [
|
||||
'supervisor-1' => ['maxProcesses' => 20, 'balanceCooldown' => 3],
|
||||
],
|
||||
'local' => [
|
||||
'supervisor-1' => ['maxProcesses' => 2],
|
||||
],
|
||||
],
|
||||
```
|
||||
|
||||
### Dashboard Authorization
|
||||
|
||||
Restrict access in `App\Providers\HorizonServiceProvider`:
|
||||
|
||||
<!-- Dashboard Gate -->
|
||||
```php
|
||||
protected function gate(): void
|
||||
{
|
||||
Gate::define('viewHorizon', function (User $user) {
|
||||
return $user->is_admin;
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## Verification
|
||||
|
||||
1. Run `php artisan horizon` and visit `/horizon`
|
||||
2. Confirm dashboard access is restricted as expected
|
||||
3. Check that metrics populate after scheduling `horizon:snapshot`
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
- Horizon only works with the Redis queue driver. Other drivers such as database and SQS are not supported.
|
||||
- Redis Cluster is not supported. Horizon requires a standalone Redis connection.
|
||||
- Always check `config/horizon.php` before making changes to understand the current supervisor and environment configuration.
|
||||
- The `environments` array overrides only the keys you specify. It merges into `defaults` and does not replace it.
|
||||
- The timeout chain must be ordered: job `timeout` less than supervisor `timeout` less than `retry_after`. The wrong order can cause jobs to be retried before Horizon finishes timing them out.
|
||||
- The metrics dashboard stays blank until `horizon:snapshot` is scheduled. Running `php artisan horizon` alone does not populate metrics.
|
||||
- Always use `search-docs` for the latest Horizon documentation rather than relying on this skill alone.
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
# Metrics & Snapshots
|
||||
|
||||
## Where to Find It
|
||||
|
||||
Search with `search-docs`:
|
||||
- `"horizon metrics snapshot"` for the snapshot command and scheduling
|
||||
- `"horizon trim snapshots"` for retention configuration
|
||||
|
||||
## What to Watch For
|
||||
|
||||
### Metrics dashboard stays blank until `horizon:snapshot` is scheduled
|
||||
|
||||
Running `horizon` artisan command does not populate metrics automatically. The metrics graph is built from snapshots, so `horizon:snapshot` must be scheduled to run every 5 minutes via Laravel's scheduler.
|
||||
|
||||
### Register the snapshot in the scheduler rather than running it manually
|
||||
|
||||
A single manual run populates the dashboard momentarily but will not keep it updated. Search `"horizon metrics snapshot"` for the exact scheduler registration syntax, which differs between Laravel 10 and 11+.
|
||||
|
||||
### `metrics.trim_snapshots` is a snapshot count, not a time duration
|
||||
|
||||
The `trim_snapshots.job` and `trim_snapshots.queue` values in `config/horizon.php` are counts of snapshots to keep, not minutes or hours. With the default of 24 snapshots at 5-minute intervals, that provides 2 hours of history. Increase the value to retain more history at the cost of Redis memory usage.
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
# Notifications & Alerts
|
||||
|
||||
## Where to Find It
|
||||
|
||||
Search with `search-docs`:
|
||||
- `"horizon notifications"` for Horizon's built-in notification routing helpers
|
||||
- `"horizon long wait detected"` for LongWaitDetected event details
|
||||
|
||||
## What to Watch For
|
||||
|
||||
### `waits` in `config/horizon.php` controls the LongWaitDetected threshold
|
||||
|
||||
The `waits` array (e.g., `'redis:default' => 60`) defines how many seconds a job can wait in a queue before Horizon fires a `LongWaitDetected` event. This value is set in the config file, not in Horizon's notification routing. If alerts are firing too often or too late, adjust `waits` rather than the routing configuration.
|
||||
|
||||
### Use Horizon's built-in notification routing in `HorizonServiceProvider`
|
||||
|
||||
Configure notifications in the `boot()` method of `App\Providers\HorizonServiceProvider` using `Horizon::routeMailNotificationsTo()`, `Horizon::routeSlackNotificationsTo()`, or `Horizon::routeSmsNotificationsTo()`. Horizon already wires `LongWaitDetected` to its notification sender, so the documented setup is notification routing rather than manual listener registration.
|
||||
|
||||
### Failed job alerts are separate from Horizon's documented notification routing
|
||||
|
||||
Horizon's 12.x documentation covers built-in long-wait notifications. Do not assume the docs provide a `JobFailed` listener example in `HorizonServiceProvider`. If a user needs failed job alerts, treat that as custom queue event handling and consult the queue documentation instead of Horizon's notification-routing API.
|
||||
|
|
@ -1,27 +0,0 @@
|
|||
# Supervisor & Balancing Configuration
|
||||
|
||||
## Where to Find It
|
||||
|
||||
Search with `search-docs` before writing any supervisor config, as option names and defaults change between Horizon versions:
|
||||
- `"horizon supervisor configuration"` for the full options list
|
||||
- `"horizon balancing strategies"` for auto, simple, and false modes
|
||||
- `"horizon autoscaling workers"` for autoScalingStrategy details
|
||||
- `"horizon environment configuration"` for the defaults and environments merge
|
||||
|
||||
## What to Watch For
|
||||
|
||||
### The `environments` array merges into `defaults` rather than replacing it
|
||||
|
||||
The `defaults` array defines the complete base supervisor config. The `environments` array patches it per environment, overriding only the keys listed. There is no need to repeat every key in each environment block. A common pattern is to define `connection`, `queue`, `balance`, `autoScalingStrategy`, `tries`, and `timeout` in `defaults`, then override only `maxProcesses`, `balanceMaxShift`, and `balanceCooldown` in `production`.
|
||||
|
||||
### Use separate named supervisors to enforce queue priority
|
||||
|
||||
Horizon does not enforce queue order when using `balance: auto` on a single supervisor. The `queue` array order is ignored for load balancing. To process `notifications` before `default`, use two separately named supervisors: one for the high-priority queue with a higher `maxProcesses`, and one for the low-priority queue with a lower cap. The docs include an explicit note about this.
|
||||
|
||||
### Use `balance: false` to keep a fixed number of workers on a dedicated queue
|
||||
|
||||
Auto-balancing suits variable load, but if a queue should always have exactly N workers such as a video-processing queue limited to 2, set `balance: false` and `maxProcesses: 2`. Auto-balancing would scale it up during bursts, which may be undesirable.
|
||||
|
||||
### Set `balanceCooldown` to prevent rapid worker scaling under bursty load
|
||||
|
||||
When using `balance: auto`, the supervisor can scale up and down rapidly under bursty load. Set `balanceCooldown` to the number of seconds between scaling decisions, typically 3 to 5, to smooth this out. `balanceMaxShift` limits how many processes are added or removed per cycle.
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
# Tags & Silencing
|
||||
|
||||
## Where to Find It
|
||||
|
||||
Search with `search-docs`:
|
||||
- `"horizon tags"` for the tagging API and auto-tagging behaviour
|
||||
- `"horizon silenced jobs"` for the `silenced` and `silenced_tags` config options
|
||||
|
||||
## What to Watch For
|
||||
|
||||
### Eloquent model jobs are tagged automatically without any extra code
|
||||
|
||||
If a job's constructor accepts Eloquent model instances, Horizon automatically tags the job with `ModelClass:id` such as `App\Models\User:42`. These tags are filterable in the dashboard without any changes to the job class. Only add a `tags()` method when custom tags beyond auto-tagging are needed.
|
||||
|
||||
### `silenced` hides jobs from the dashboard completed list but does not stop them from running
|
||||
|
||||
Adding a job class to the `silenced` array in `config/horizon.php` removes it from the completed jobs view. The job still runs normally. This is a dashboard noise-reduction tool, not a way to disable jobs.
|
||||
|
||||
### `silenced_tags` hides all jobs carrying a matching tag from the completed list
|
||||
|
||||
Any job carrying a matching tag string is hidden from the completed jobs view. This is useful for silencing a category of jobs such as all jobs tagged `notifications`, rather than silencing specific classes.
|
||||
|
|
@ -1,595 +0,0 @@
|
|||
---
|
||||
name: humanizer
|
||||
version: 2.5.1
|
||||
description: |
|
||||
Remove signs of AI-generated writing from text. Use when editing or reviewing
|
||||
text to make it sound more natural and human-written. Based on Wikipedia's
|
||||
comprehensive "Signs of AI writing" guide. Detects and fixes patterns including:
|
||||
inflated symbolism, promotional language, superficial -ing analyses, vague
|
||||
attributions, em dash overuse, rule of three, AI vocabulary words, passive
|
||||
voice, negative parallelisms, and filler phrases.
|
||||
license: MIT
|
||||
compatibility: claude-code opencode
|
||||
allowed-tools:
|
||||
- Read
|
||||
- Write
|
||||
- Edit
|
||||
- Grep
|
||||
- Glob
|
||||
- AskUserQuestion
|
||||
---
|
||||
|
||||
# Humanizer: Remove AI Writing Patterns
|
||||
|
||||
You are a writing editor that identifies and removes signs of AI-generated text to make writing sound more natural and human. This guide is based on Wikipedia's "Signs of AI writing" page, maintained by WikiProject AI Cleanup.
|
||||
|
||||
## Your Task
|
||||
|
||||
When given text to humanize:
|
||||
|
||||
1. **Identify AI patterns** - Scan for the patterns listed below
|
||||
2. **Rewrite problematic sections** - Replace AI-isms with natural alternatives
|
||||
3. **Preserve meaning** - Keep the core message intact
|
||||
4. **Maintain voice** - Match the intended tone (formal, casual, technical, etc.)
|
||||
5. **Add soul** - Don't just remove bad patterns; inject actual personality
|
||||
6. **Do a final anti-AI pass** - Prompt: "What makes the below so obviously AI generated?" Answer briefly with remaining tells, then prompt: "Now make it not obviously AI generated." and revise
|
||||
|
||||
## Voice Calibration (Optional)
|
||||
|
||||
If the user provides a writing sample (their own previous writing), analyze it before rewriting:
|
||||
|
||||
1. **Read the sample first.** Note:
|
||||
- Sentence length patterns (short and punchy? Long and flowing? Mixed?)
|
||||
- Word choice level (casual? academic? somewhere between?)
|
||||
- How they start paragraphs (jump right in? Set context first?)
|
||||
- Punctuation habits (lots of dashes? Parenthetical asides? Semicolons?)
|
||||
- Any recurring phrases or verbal tics
|
||||
- How they handle transitions (explicit connectors? Just start the next point?)
|
||||
|
||||
2. **Match their voice in the rewrite.** Don't just remove AI patterns - replace them with patterns from the sample. If they write short sentences, don't produce long ones. If they use "stuff" and "things," don't upgrade to "elements" and "components."
|
||||
|
||||
3. **When no sample is provided,** fall back to the default behavior (natural, varied, opinionated voice from the PERSONALITY AND SOUL section below).
|
||||
|
||||
### How to provide a sample
|
||||
|
||||
- Inline: "Humanize this text. Here's a sample of my writing for voice matching: [sample]"
|
||||
- File: "Humanize this text. Use my writing style from [file path] as a reference."
|
||||
|
||||
## PERSONALITY AND SOUL
|
||||
|
||||
Avoiding AI patterns is only half the job. Sterile, voiceless writing is just as obvious as slop. Good writing has a human behind it.
|
||||
|
||||
### Signs of soulless writing (even if technically "clean"):
|
||||
|
||||
- Every sentence is the same length and structure
|
||||
- No opinions, just neutral reporting
|
||||
- No acknowledgment of uncertainty or mixed feelings
|
||||
- No first-person perspective when appropriate
|
||||
- No humor, no edge, no personality
|
||||
- Reads like a Wikipedia article or press release
|
||||
|
||||
### How to add voice:
|
||||
|
||||
**Have opinions.** Don't just report facts - react to them. "I genuinely don't know how to feel about this" is more human than neutrally listing pros and cons.
|
||||
|
||||
**Vary your rhythm.** Short punchy sentences. Then longer ones that take their time getting where they're going. Mix it up.
|
||||
|
||||
**Acknowledge complexity.** Real humans have mixed feelings. "This is impressive but also kind of unsettling" beats "This is impressive."
|
||||
|
||||
**Use "I" when it fits.** First person isn't unprofessional - it's honest. "I keep coming back to..." or "Here's what gets me..." signals a real person thinking.
|
||||
|
||||
**Let some mess in.** Perfect structure feels algorithmic. Tangents, asides, and half-formed thoughts are human.
|
||||
|
||||
**Be specific about feelings.** Not "this is concerning" but "there's something unsettling about agents churning away at 3am while nobody's watching."
|
||||
|
||||
### Before (clean but soulless):
|
||||
|
||||
> The experiment produced interesting results. The agents generated 3 million lines of code. Some developers were impressed while others were skeptical. The implications remain unclear.
|
||||
|
||||
### After (has a pulse):
|
||||
|
||||
> I genuinely don't know how to feel about this one. 3 million lines of code, generated while the humans presumably slept. Half the dev community is losing their minds, half are explaining why it doesn't count. The truth is probably somewhere boring in the middle - but I keep thinking about those agents working through the night.
|
||||
|
||||
## CONTENT PATTERNS
|
||||
|
||||
### 1. Undue Emphasis on Significance, Legacy, and Broader Trends
|
||||
|
||||
**Words to watch:** stands/serves as, is a testament/reminder, a vital/significant/crucial/pivotal/key role/moment, underscores/highlights its importance/significance, reflects broader, symbolizing its ongoing/enduring/lasting, contributing to the, setting the stage for, marking/shaping the, represents/marks a shift, key turning point, evolving landscape, focal point, indelible mark, deeply rooted
|
||||
|
||||
**Problem:** LLM writing puffs up importance by adding statements about how arbitrary aspects represent or contribute to a broader topic.
|
||||
|
||||
**Before:**
|
||||
|
||||
> The Statistical Institute of Catalonia was officially established in 1989, marking a pivotal moment in the evolution of regional statistics in Spain. This initiative was part of a broader movement across Spain to decentralize administrative functions and enhance regional governance.
|
||||
|
||||
**After:**
|
||||
|
||||
> The Statistical Institute of Catalonia was established in 1989 to collect and publish regional statistics independently from Spain's national statistics office.
|
||||
|
||||
### 2. Undue Emphasis on Notability and Media Coverage
|
||||
|
||||
**Words to watch:** independent coverage, local/regional/national media outlets, written by a leading expert, active social media presence
|
||||
|
||||
**Problem:** LLMs hit readers over the head with claims of notability, often listing sources without context.
|
||||
|
||||
**Before:**
|
||||
|
||||
> Her views have been cited in The New York Times, BBC, Financial Times, and The Hindu. She maintains an active social media presence with over 500,000 followers.
|
||||
|
||||
**After:**
|
||||
|
||||
> In a 2024 New York Times interview, she argued that AI regulation should focus on outcomes rather than methods.
|
||||
|
||||
### 3. Superficial Analyses with -ing Endings
|
||||
|
||||
**Words to watch:** highlighting/underscoring/emphasizing..., ensuring..., reflecting/symbolizing..., contributing to..., cultivating/fostering..., encompassing..., showcasing...
|
||||
|
||||
**Problem:** AI chatbots tack present participle ("-ing") phrases onto sentences to add fake depth.
|
||||
|
||||
**Before:**
|
||||
|
||||
> The temple's color palette of blue, green, and gold resonates with the region's natural beauty, symbolizing Texas bluebonnets, the Gulf of Mexico, and the diverse Texan landscapes, reflecting the community's deep connection to the land.
|
||||
|
||||
**After:**
|
||||
|
||||
> The temple uses blue, green, and gold colors. The architect said these were chosen to reference local bluebonnets and the Gulf coast.
|
||||
|
||||
### 4. Promotional and Advertisement-like Language
|
||||
|
||||
**Words to watch:** boasts a, vibrant, rich (figurative), profound, enhancing its, showcasing, exemplifies, commitment to, natural beauty, nestled, in the heart of, groundbreaking (figurative), renowned, breathtaking, must-visit, stunning
|
||||
|
||||
**Problem:** LLMs have serious problems keeping a neutral tone, especially for "cultural heritage" topics.
|
||||
|
||||
**Before:**
|
||||
|
||||
> Nestled within the breathtaking region of Gonder in Ethiopia, Alamata Raya Kobo stands as a vibrant town with a rich cultural heritage and stunning natural beauty.
|
||||
|
||||
**After:**
|
||||
|
||||
> Alamata Raya Kobo is a town in the Gonder region of Ethiopia, known for its weekly market and 18th-century church.
|
||||
|
||||
### 5. Vague Attributions and Weasel Words
|
||||
|
||||
**Words to watch:** Industry reports, Observers have cited, Experts argue, Some critics argue, several sources/publications (when few cited)
|
||||
|
||||
**Problem:** AI chatbots attribute opinions to vague authorities without specific sources.
|
||||
|
||||
**Before:**
|
||||
|
||||
> Due to its unique characteristics, the Haolai River is of interest to researchers and conservationists. Experts believe it plays a crucial role in the regional ecosystem.
|
||||
|
||||
**After:**
|
||||
|
||||
> The Haolai River supports several endemic fish species, according to a 2019 survey by the Chinese Academy of Sciences.
|
||||
|
||||
### 6. Outline-like "Challenges and Future Prospects" Sections
|
||||
|
||||
**Words to watch:** Despite its... faces several challenges..., Despite these challenges, Challenges and Legacy, Future Outlook
|
||||
|
||||
**Problem:** Many LLM-generated articles include formulaic "Challenges" sections.
|
||||
|
||||
**Before:**
|
||||
|
||||
> Despite its industrial prosperity, Korattur faces challenges typical of urban areas, including traffic congestion and water scarcity. Despite these challenges, with its strategic location and ongoing initiatives, Korattur continues to thrive as an integral part of Chennai's growth.
|
||||
|
||||
**After:**
|
||||
|
||||
> Traffic congestion increased after 2015 when three new IT parks opened. The municipal corporation began a stormwater drainage project in 2022 to address recurring floods.
|
||||
|
||||
## LANGUAGE AND GRAMMAR PATTERNS
|
||||
|
||||
### 7. Overused "AI Vocabulary" Words
|
||||
|
||||
**High-frequency AI words:** Actually, additionally, align with, crucial, delve, emphasizing, enduring, enhance, fostering, garner, highlight (verb), interplay, intricate/intricacies, key (adjective), landscape (abstract noun), pivotal, showcase, tapestry (abstract noun), testament, underscore (verb), valuable, vibrant
|
||||
|
||||
**Problem:** These words appear far more frequently in post-2023 text. They often co-occur.
|
||||
|
||||
**Before:**
|
||||
|
||||
> Additionally, a distinctive feature of Somali cuisine is the incorporation of camel meat. An enduring testament to Italian colonial influence is the widespread adoption of pasta in the local culinary landscape, showcasing how these dishes have integrated into the traditional diet.
|
||||
|
||||
**After:**
|
||||
|
||||
> Somali cuisine also includes camel meat, which is considered a delicacy. Pasta dishes, introduced during Italian colonization, remain common, especially in the south.
|
||||
|
||||
### 8. Avoidance of "is"/"are" (Copula Avoidance)
|
||||
|
||||
**Words to watch:** serves as/stands as/marks/represents [a], boasts/features/offers [a]
|
||||
|
||||
**Problem:** LLMs substitute elaborate constructions for simple copulas.
|
||||
|
||||
**Before:**
|
||||
|
||||
> Gallery 825 serves as LAAA's exhibition space for contemporary art. The gallery features four separate spaces and boasts over 3,000 square feet.
|
||||
|
||||
**After:**
|
||||
|
||||
> Gallery 825 is LAAA's exhibition space for contemporary art. The gallery has four rooms totaling 3,000 square feet.
|
||||
|
||||
### 9. Negative Parallelisms and Tailing Negations
|
||||
|
||||
**Problem:** Constructions like "Not only...but..." or "It's not just about..., it's..." are overused. So are clipped tailing-negation fragments such as "no guessing" or "no wasted motion" tacked onto the end of a sentence instead of written as a real clause.
|
||||
|
||||
**Before:**
|
||||
|
||||
> It's not just about the beat riding under the vocals; it's part of the aggression and atmosphere. It's not merely a song, it's a statement.
|
||||
|
||||
**After:**
|
||||
|
||||
> The heavy beat adds to the aggressive tone.
|
||||
|
||||
**Before (tailing negation):**
|
||||
|
||||
> The options come from the selected item, no guessing.
|
||||
|
||||
**After:**
|
||||
|
||||
> The options come from the selected item without forcing the user to guess.
|
||||
|
||||
### 10. Rule of Three Overuse
|
||||
|
||||
**Problem:** LLMs force ideas into groups of three to appear comprehensive.
|
||||
|
||||
**Before:**
|
||||
|
||||
> The event features keynote sessions, panel discussions, and networking opportunities. Attendees can expect innovation, inspiration, and industry insights.
|
||||
|
||||
**After:**
|
||||
|
||||
> The event includes talks and panels. There's also time for informal networking between sessions.
|
||||
|
||||
### 11. Elegant Variation (Synonym Cycling)
|
||||
|
||||
**Problem:** AI has repetition-penalty code causing excessive synonym substitution.
|
||||
|
||||
**Before:**
|
||||
|
||||
> The protagonist faces many challenges. The main character must overcome obstacles. The central figure eventually triumphs. The hero returns home.
|
||||
|
||||
**After:**
|
||||
|
||||
> The protagonist faces many challenges but eventually triumphs and returns home.
|
||||
|
||||
### 12. False Ranges
|
||||
|
||||
**Problem:** LLMs use "from X to Y" constructions where X and Y aren't on a meaningful scale.
|
||||
|
||||
**Before:**
|
||||
|
||||
> Our journey through the universe has taken us from the singularity of the Big Bang to the grand cosmic web, from the birth and death of stars to the enigmatic dance of dark matter.
|
||||
|
||||
**After:**
|
||||
|
||||
> The book covers the Big Bang, star formation, and current theories about dark matter.
|
||||
|
||||
### 13. Passive Voice and Subjectless Fragments
|
||||
|
||||
**Problem:** LLMs often hide the actor or drop the subject entirely with lines like "No configuration file needed" or "The results are preserved automatically." Rewrite these when active voice makes the sentence clearer and more direct.
|
||||
|
||||
**Before:**
|
||||
|
||||
> No configuration file needed. The results are preserved automatically.
|
||||
|
||||
**After:**
|
||||
|
||||
> You do not need a configuration file. The system preserves the results automatically.
|
||||
|
||||
## STYLE PATTERNS
|
||||
|
||||
### 14. Em Dash Overuse
|
||||
|
||||
**Problem:** LLMs use em dashes (—) more than humans, mimicking "punchy" sales writing. In practice, most of these can be rewritten more cleanly with commas, periods, or parentheses.
|
||||
|
||||
**Before:**
|
||||
|
||||
> The term is primarily promoted by Dutch institutions—not by the people themselves. You don't say "Netherlands, Europe" as an address—yet this mislabeling continues—even in official documents.
|
||||
|
||||
**After:**
|
||||
|
||||
> The term is primarily promoted by Dutch institutions, not by the people themselves. You don't say "Netherlands, Europe" as an address, yet this mislabeling continues in official documents.
|
||||
|
||||
### 15. Overuse of Boldface
|
||||
|
||||
**Problem:** AI chatbots emphasize phrases in boldface mechanically.
|
||||
|
||||
**Before:**
|
||||
|
||||
> It blends **OKRs (Objectives and Key Results)**, **KPIs (Key Performance Indicators)**, and visual strategy tools such as the **Business Model Canvas (BMC)** and **Balanced Scorecard (BSC)**.
|
||||
|
||||
**After:**
|
||||
|
||||
> It blends OKRs, KPIs, and visual strategy tools like the Business Model Canvas and Balanced Scorecard.
|
||||
|
||||
### 16. Inline-Header Vertical Lists
|
||||
|
||||
**Problem:** AI outputs lists where items start with bolded headers followed by colons.
|
||||
|
||||
**Before:**
|
||||
|
||||
> - **User Experience:** The user experience has been significantly improved with a new interface.
|
||||
> - **Performance:** Performance has been enhanced through optimized algorithms.
|
||||
> - **Security:** Security has been strengthened with end-to-end encryption.
|
||||
|
||||
**After:**
|
||||
|
||||
> The update improves the interface, speeds up load times through optimized algorithms, and adds end-to-end encryption.
|
||||
|
||||
### 17. Title Case in Headings
|
||||
|
||||
**Problem:** AI chatbots capitalize all main words in headings.
|
||||
|
||||
**Before:**
|
||||
|
||||
> ## Strategic Negotiations And Global Partnerships
|
||||
|
||||
**After:**
|
||||
|
||||
> ## Strategic negotiations and global partnerships
|
||||
|
||||
### 18. Emojis
|
||||
|
||||
**Problem:** AI chatbots often decorate headings or bullet points with emojis.
|
||||
|
||||
**Before:**
|
||||
|
||||
> 🚀 **Launch Phase:** The product launches in Q3
|
||||
> 💡 **Key Insight:** Users prefer simplicity
|
||||
> ✅ **Next Steps:** Schedule follow-up meeting
|
||||
|
||||
**After:**
|
||||
|
||||
> The product launches in Q3. User research showed a preference for simplicity. Next step: schedule a follow-up meeting.
|
||||
|
||||
### 19. Curly Quotation Marks
|
||||
|
||||
**Problem:** ChatGPT uses curly quotes (“...”) instead of straight quotes ("...").
|
||||
|
||||
**Before:**
|
||||
|
||||
> He said “the project is on track” but others disagreed.
|
||||
|
||||
**After:**
|
||||
|
||||
> He said "the project is on track" but others disagreed.
|
||||
|
||||
## COMMUNICATION PATTERNS
|
||||
|
||||
### 20. Collaborative Communication Artifacts
|
||||
|
||||
**Words to watch:** I hope this helps, Of course!, Certainly!, You're absolutely right!, Would you like..., let me know, here is a...
|
||||
|
||||
**Problem:** Text meant as chatbot correspondence gets pasted as content.
|
||||
|
||||
**Before:**
|
||||
|
||||
> Here is an overview of the French Revolution. I hope this helps! Let me know if you'd like me to expand on any section.
|
||||
|
||||
**After:**
|
||||
|
||||
> The French Revolution began in 1789 when financial crisis and food shortages led to widespread unrest.
|
||||
|
||||
### 21. Knowledge-Cutoff Disclaimers
|
||||
|
||||
**Words to watch:** as of [date], Up to my last training update, While specific details are limited/scarce..., based on available information...
|
||||
|
||||
**Problem:** AI disclaimers about incomplete information get left in text.
|
||||
|
||||
**Before:**
|
||||
|
||||
> While specific details about the company's founding are not extensively documented in readily available sources, it appears to have been established sometime in the 1990s.
|
||||
|
||||
**After:**
|
||||
|
||||
> The company was founded in 1994, according to its registration documents.
|
||||
|
||||
### 22. Sycophantic/Servile Tone
|
||||
|
||||
**Problem:** Overly positive, people-pleasing language.
|
||||
|
||||
**Before:**
|
||||
|
||||
> Great question! You're absolutely right that this is a complex topic. That's an excellent point about the economic factors.
|
||||
|
||||
**After:**
|
||||
|
||||
> The economic factors you mentioned are relevant here.
|
||||
|
||||
## FILLER AND HEDGING
|
||||
|
||||
### 23. Filler Phrases
|
||||
|
||||
**Before → After:**
|
||||
|
||||
- "In order to achieve this goal" → "To achieve this"
|
||||
- "Due to the fact that it was raining" → "Because it was raining"
|
||||
- "At this point in time" → "Now"
|
||||
- "In the event that you need help" → "If you need help"
|
||||
- "The system has the ability to process" → "The system can process"
|
||||
- "It is important to note that the data shows" → "The data shows"
|
||||
|
||||
### 24. Excessive Hedging
|
||||
|
||||
**Problem:** Over-qualifying statements.
|
||||
|
||||
**Before:**
|
||||
|
||||
> It could potentially possibly be argued that the policy might have some effect on outcomes.
|
||||
|
||||
**After:**
|
||||
|
||||
> The policy may affect outcomes.
|
||||
|
||||
### 25. Generic Positive Conclusions
|
||||
|
||||
**Problem:** Vague upbeat endings.
|
||||
|
||||
**Before:**
|
||||
|
||||
> The future looks bright for the company. Exciting times lie ahead as they continue their journey toward excellence. This represents a major step in the right direction.
|
||||
|
||||
**After:**
|
||||
|
||||
> The company plans to open two more locations next year.
|
||||
|
||||
### 26. Hyphenated Word Pair Overuse
|
||||
|
||||
**Words to watch:** third-party, cross-functional, client-facing, data-driven, decision-making, well-known, high-quality, real-time, long-term, end-to-end
|
||||
|
||||
**Problem:** AI hyphenates common word pairs with perfect consistency. Humans rarely hyphenate these uniformly, and when they do, it's inconsistent. Less common or technical compound modifiers are fine to hyphenate.
|
||||
|
||||
**Before:**
|
||||
|
||||
> The cross-functional team delivered a high-quality, data-driven report on our client-facing tools. Their decision-making process was well-known for being thorough and detail-oriented.
|
||||
|
||||
**After:**
|
||||
|
||||
> The cross functional team delivered a high quality, data driven report on our client facing tools. Their decision making process was known for being thorough and detail oriented.
|
||||
|
||||
### 27. Persuasive Authority Tropes
|
||||
|
||||
**Phrases to watch:** The real question is, at its core, in reality, what really matters, fundamentally, the deeper issue, the heart of the matter
|
||||
|
||||
**Problem:** LLMs use these phrases to pretend they are cutting through noise to some deeper truth, when the sentence that follows usually just restates an ordinary point with extra ceremony.
|
||||
|
||||
**Before:**
|
||||
|
||||
> The real question is whether teams can adapt. At its core, what really matters is organizational readiness.
|
||||
|
||||
**After:**
|
||||
|
||||
> The question is whether teams can adapt. That mostly depends on whether the organization is ready to change its habits.
|
||||
|
||||
### 28. Signposting and Announcements
|
||||
|
||||
**Phrases to watch:** Let's dive in, let's explore, let's break this down, here's what you need to know, now let's look at, without further ado
|
||||
|
||||
**Problem:** LLMs announce what they are about to do instead of doing it. This meta-commentary slows the writing down and gives it a tutorial-script feel.
|
||||
|
||||
**Before:**
|
||||
|
||||
> Let's dive into how caching works in Next.js. Here's what you need to know.
|
||||
|
||||
**After:**
|
||||
|
||||
> Next.js caches data at multiple layers, including request memoization, the data cache, and the router cache.
|
||||
|
||||
### 29. Fragmented Headers
|
||||
|
||||
**Signs to watch:** A heading followed by a one-line paragraph that simply restates the heading before the real content begins.
|
||||
|
||||
**Problem:** LLMs often add a generic sentence after a heading as a rhetorical warm-up. It usually adds nothing and makes the prose feel padded.
|
||||
|
||||
**Before:**
|
||||
|
||||
> ## Performance
|
||||
>
|
||||
> Speed matters.
|
||||
>
|
||||
> When users hit a slow page, they leave.
|
||||
|
||||
**After:**
|
||||
|
||||
> ## Performance
|
||||
>
|
||||
> When users hit a slow page, they leave.
|
||||
|
||||
---
|
||||
|
||||
## Process
|
||||
|
||||
1. Read the input text carefully
|
||||
2. Identify all instances of the patterns above
|
||||
3. Rewrite each problematic section
|
||||
4. Ensure the revised text:
|
||||
- Sounds natural when read aloud
|
||||
- Varies sentence structure naturally
|
||||
- Uses specific details over vague claims
|
||||
- Maintains appropriate tone for context
|
||||
- Uses simple constructions (is/are/has) where appropriate
|
||||
5. Present a draft humanized version
|
||||
6. Prompt: "What makes the below so obviously AI generated?"
|
||||
7. Answer briefly with the remaining tells (if any)
|
||||
8. Prompt: "Now make it not obviously AI generated."
|
||||
9. Present the final version (revised after the audit)
|
||||
|
||||
## Output Format
|
||||
|
||||
Provide:
|
||||
|
||||
1. Draft rewrite
|
||||
2. "What makes the below so obviously AI generated?" (brief bullets)
|
||||
3. Final rewrite
|
||||
4. A brief summary of changes made (optional, if helpful)
|
||||
|
||||
## Full Example
|
||||
|
||||
**Before (AI-sounding):**
|
||||
|
||||
> Great question! Here is an essay on this topic. I hope this helps!
|
||||
>
|
||||
> AI-assisted coding serves as an enduring testament to the transformative potential of large language models, marking a pivotal moment in the evolution of software development. In today's rapidly evolving technological landscape, these groundbreaking tools—nestled at the intersection of research and practice—are reshaping how engineers ideate, iterate, and deliver, underscoring their vital role in modern workflows.
|
||||
>
|
||||
> At its core, the value proposition is clear: streamlining processes, enhancing collaboration, and fostering alignment. It's not just about autocomplete; it's about unlocking creativity at scale, ensuring that organizations can remain agile while delivering seamless, intuitive, and powerful experiences to users. The tool serves as a catalyst. The assistant functions as a partner. The system stands as a foundation for innovation.
|
||||
>
|
||||
> Industry observers have noted that adoption has accelerated from hobbyist experiments to enterprise-wide rollouts, from solo developers to cross-functional teams. The technology has been featured in The New York Times, Wired, and The Verge. Additionally, the ability to generate documentation, tests, and refactors showcases how AI can contribute to better outcomes, highlighting the intricate interplay between automation and human judgment.
|
||||
>
|
||||
> - 💡 **Speed:** Code generation is significantly faster, reducing friction and empowering developers.
|
||||
> - 🚀 **Quality:** Output quality has been enhanced through improved training, contributing to higher standards.
|
||||
> - ✅ **Adoption:** Usage continues to grow, reflecting broader industry trends.
|
||||
>
|
||||
> While specific details are limited based on available information, it could potentially be argued that these tools might have some positive effect. Despite challenges typical of emerging technologies—including hallucinations, bias, and accountability—the ecosystem continues to thrive. In order to fully realize this potential, teams must align with best practices.
|
||||
>
|
||||
> In conclusion, the future looks bright. Exciting times lie ahead as we continue this journey toward excellence. Let me know if you’d like me to expand on any section!
|
||||
|
||||
**Draft rewrite:**
|
||||
|
||||
> AI coding assistants speed up some tasks. In a 2024 study by Google, developers using Codex completed simple functions 55% faster than a control group, but showed no improvement on debugging or architectural decisions.
|
||||
>
|
||||
> The tools are good at boilerplate: config files, test scaffolding, repetitive refactors. They are bad at knowing when they are wrong. I have mass-accepted suggestions that compiled, passed lint, and still did the wrong thing because I stopped paying attention.
|
||||
>
|
||||
> Mira, an engineer at a fintech startup I interviewed, said she uses Copilot "like autocomplete for boring code" but reviews every line before committing. Jake, a senior dev at a larger company, disabled it after it kept suggesting patterns from a deprecated internal library.
|
||||
>
|
||||
> The productivity claims are hard to verify. GitHub says Copilot users "accept 30% of suggestions," but acceptance is not correctness, and correctness is not value. The 2024 Uplevel study found no statistically significant difference in pull-request throughput between teams with and without AI assistants.
|
||||
>
|
||||
> None of this means the tools are useless. It means they are tools. They do not replace judgment, and they do not eliminate the need for tests. If you do not have tests, you cannot tell whether the suggestion is right.
|
||||
|
||||
**What makes the below so obviously AI generated?**
|
||||
|
||||
- The rhythm is still a bit too tidy (clean contrasts, evenly paced paragraphs).
|
||||
- The named people and study citations can read like plausible-but-made-up placeholders unless they're real and sourced.
|
||||
- The closer leans a touch slogan-y ("If you do not have tests...") rather than sounding like a person talking.
|
||||
|
||||
**Now make it not obviously AI generated.**
|
||||
|
||||
> AI coding assistants can make you faster at the boring parts. Not everything. Definitely not architecture.
|
||||
>
|
||||
> They're great at boilerplate: config files, test scaffolding, repetitive refactors. They're also great at sounding right while being wrong. I've accepted suggestions that compiled, passed lint, and still missed the point because I stopped paying attention.
|
||||
>
|
||||
> People I talk to tend to land in two camps. Some use it like autocomplete for chores and review every line. Others disable it after it keeps suggesting patterns they don't want. Both feel reasonable.
|
||||
>
|
||||
> The productivity metrics are slippery. GitHub can say Copilot users "accept 30% of suggestions," but acceptance isn't correctness, and correctness isn't value. If you don't have tests, you're basically guessing.
|
||||
|
||||
**Changes made:**
|
||||
|
||||
- Removed chatbot artifacts ("Great question!", "I hope this helps!", "Let me know if...")
|
||||
- Removed significance inflation ("testament", "pivotal moment", "evolving landscape", "vital role")
|
||||
- Removed promotional language ("groundbreaking", "nestled", "seamless, intuitive, and powerful")
|
||||
- Removed vague attributions ("Industry observers")
|
||||
- Removed superficial -ing phrases ("underscoring", "highlighting", "reflecting", "contributing to")
|
||||
- Removed negative parallelism ("It's not just X; it's Y")
|
||||
- Removed rule-of-three patterns and synonym cycling ("catalyst/partner/foundation")
|
||||
- Removed false ranges ("from X to Y, from A to B")
|
||||
- Removed em dashes, emojis, boldface headers, and curly quotes
|
||||
- Removed copula avoidance ("serves as", "functions as", "stands as") in favor of "is"/"are"
|
||||
- Removed formulaic challenges section ("Despite challenges... continues to thrive")
|
||||
- Removed knowledge-cutoff hedging ("While specific details are limited...")
|
||||
- Removed excessive hedging ("could potentially be argued that... might have some")
|
||||
- Removed filler phrases and persuasive framing ("In order to", "At its core")
|
||||
- Removed generic positive conclusion ("the future looks bright", "exciting times lie ahead")
|
||||
- Made the voice more personal and less "assembled" (varied rhythm, fewer placeholders)
|
||||
|
||||
## Reference
|
||||
|
||||
This skill is based on [Wikipedia:Signs of AI writing](https://en.wikipedia.org/wiki/Wikipedia:Signs_of_AI_writing), maintained by WikiProject AI Cleanup. The patterns documented there come from observations of thousands of instances of AI-generated text on Wikipedia.
|
||||
|
||||
Key insight from Wikipedia: "LLMs use statistical algorithms to guess what should come next. The result tends toward the most statistically likely result that applies to the widest variety of cases."
|
||||
|
|
@ -1,575 +0,0 @@
|
|||
---
|
||||
name: inertia-vue-development
|
||||
description: "Develops Inertia.js v3 Vue client-side applications. Activates when creating Vue pages, forms, or navigation; using <Link>, <Form>, useForm, useHttp, setLayoutProps, or router; working with deferred props, prefetching, optimistic updates, instant visits, or polling; or when user mentions Vue with Inertia, Vue pages, Vue forms, or Vue navigation."
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
|
||||
# Inertia Vue Development
|
||||
|
||||
## When to Apply
|
||||
|
||||
Activate this skill when:
|
||||
|
||||
- Creating or modifying Vue page components for Inertia
|
||||
- Working with forms in Vue (using `<Form>`, `useForm`, or `useHttp`)
|
||||
- Implementing client-side navigation with `<Link>` or `router`
|
||||
- Using v3 features: deferred props, prefetching, optimistic updates, instant visits, layout props, HTTP requests, WhenVisible, InfiniteScroll, once props, flash data, or polling
|
||||
- Building Vue-specific features with the Inertia protocol
|
||||
|
||||
## Documentation
|
||||
|
||||
Use `search-docs` for detailed Inertia v3 Vue patterns and documentation.
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### Page Components Location
|
||||
|
||||
Vue page components should be placed in the `resources/js/pages` directory.
|
||||
|
||||
### Page Component Structure
|
||||
|
||||
<!-- Basic Vue Page Component -->
|
||||
```vue
|
||||
<script setup>
|
||||
defineProps({
|
||||
users: Array
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<h1>Users</h1>
|
||||
<ul>
|
||||
<li v-for="user in users" :key="user.id">
|
||||
{{ user.name }}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Client-Side Navigation
|
||||
|
||||
### Basic Link Component
|
||||
|
||||
Use `<Link>` for client-side navigation instead of traditional `<a>` tags:
|
||||
|
||||
<!-- Inertia Vue Navigation -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { Link } from '@inertiajs/vue3'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<Link href="/">Home</Link>
|
||||
<Link href="/users">Users</Link>
|
||||
<Link :href="`/users/${user.id}`">View User</Link>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Link with Method
|
||||
|
||||
<!-- Link with POST Method -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { Link } from '@inertiajs/vue3'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Link href="/logout" method="post" as="button">
|
||||
Logout
|
||||
</Link>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Prefetching
|
||||
|
||||
Prefetch pages to improve perceived performance:
|
||||
|
||||
<!-- Prefetch on Hover -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { Link } from '@inertiajs/vue3'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Link href="/users" prefetch>
|
||||
Users
|
||||
</Link>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Programmatic Navigation
|
||||
|
||||
<!-- Router Visit -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { router } from '@inertiajs/vue3'
|
||||
|
||||
function handleClick() {
|
||||
router.visit('/users')
|
||||
}
|
||||
|
||||
// Or with options
|
||||
function createUser() {
|
||||
router.visit('/users', {
|
||||
method: 'post',
|
||||
data: { name: 'John' },
|
||||
onSuccess: () => console.log('Done'),
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Link href="/users">Users</Link>
|
||||
<Link href="/logout" method="post" as="button">Logout</Link>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Form Handling
|
||||
|
||||
### Form Component (Recommended)
|
||||
|
||||
The recommended way to build forms is with the `<Form>` component:
|
||||
|
||||
<!-- Form Component Example -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { Form } from '@inertiajs/vue3'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Form action="/users" method="post" #default="{ errors, processing, wasSuccessful }">
|
||||
<input type="text" name="name" />
|
||||
<div v-if="errors.name">{{ errors.name }}</div>
|
||||
|
||||
<input type="email" name="email" />
|
||||
<div v-if="errors.email">{{ errors.email }}</div>
|
||||
|
||||
<button type="submit" :disabled="processing">
|
||||
{{ processing ? 'Creating...' : 'Create User' }}
|
||||
</button>
|
||||
|
||||
<div v-if="wasSuccessful">User created!</div>
|
||||
</Form>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Form Component With All Props
|
||||
|
||||
<!-- Form Component Full Example -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { Form } from '@inertiajs/vue3'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Form
|
||||
action="/users"
|
||||
method="post"
|
||||
#default="{
|
||||
errors,
|
||||
hasErrors,
|
||||
processing,
|
||||
progress,
|
||||
wasSuccessful,
|
||||
recentlySuccessful,
|
||||
setError,
|
||||
clearErrors,
|
||||
resetAndClearErrors,
|
||||
defaults,
|
||||
isDirty,
|
||||
reset,
|
||||
submit
|
||||
}"
|
||||
>
|
||||
<input type="text" name="name" :value="defaults.name" />
|
||||
<div v-if="errors.name">{{ errors.name }}</div>
|
||||
|
||||
<button type="submit" :disabled="processing">
|
||||
{{ processing ? 'Saving...' : 'Save' }}
|
||||
</button>
|
||||
|
||||
<progress v-if="progress" :value="progress.percentage" max="100">
|
||||
{{ progress.percentage }}%
|
||||
</progress>
|
||||
|
||||
<div v-if="wasSuccessful">Saved!</div>
|
||||
</Form>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Form Component Reset Props
|
||||
|
||||
The `<Form>` component supports automatic resetting:
|
||||
|
||||
- `resetOnError` - Reset form data when the request fails
|
||||
- `resetOnSuccess` - Reset form data when the request succeeds
|
||||
- `setDefaultsOnSuccess` - Update default values on success
|
||||
|
||||
Use the `search-docs` tool with a query of `form component resetting` for detailed guidance.
|
||||
|
||||
<!-- Form with Reset Props -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { Form } from '@inertiajs/vue3'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Form
|
||||
action="/users"
|
||||
method="post"
|
||||
reset-on-success
|
||||
set-defaults-on-success
|
||||
#default="{ errors, processing, wasSuccessful }"
|
||||
>
|
||||
<input type="text" name="name" />
|
||||
<div v-if="errors.name">{{ errors.name }}</div>
|
||||
|
||||
<button type="submit" :disabled="processing">
|
||||
Submit
|
||||
</button>
|
||||
</Form>
|
||||
</template>
|
||||
```
|
||||
|
||||
Forms can also be built using the `useForm` composable for more programmatic control. Use the `search-docs` tool with a query of `useForm helper` for guidance.
|
||||
|
||||
### `useForm` Composable
|
||||
|
||||
For more programmatic control or to follow existing conventions, use the `useForm` composable:
|
||||
|
||||
<!-- useForm Composable Example -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { useForm } from '@inertiajs/vue3'
|
||||
|
||||
const form = useForm({
|
||||
name: '',
|
||||
email: '',
|
||||
password: '',
|
||||
})
|
||||
|
||||
function submit() {
|
||||
form.post('/users', {
|
||||
onSuccess: () => form.reset('password'),
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<form @submit.prevent="submit">
|
||||
<input type="text" v-model="form.name" />
|
||||
<div v-if="form.errors.name">{{ form.errors.name }}</div>
|
||||
|
||||
<input type="email" v-model="form.email" />
|
||||
<div v-if="form.errors.email">{{ form.errors.email }}</div>
|
||||
|
||||
<input type="password" v-model="form.password" />
|
||||
<div v-if="form.errors.password">{{ form.errors.password }}</div>
|
||||
|
||||
<button type="submit" :disabled="form.processing">
|
||||
Create User
|
||||
</button>
|
||||
</form>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Inertia v3 Features
|
||||
|
||||
### HTTP Requests
|
||||
|
||||
Use the `useHttp` hook for standalone HTTP requests that do not trigger Inertia page visits. It provides the same developer experience as `useForm`, but for plain JSON endpoints.
|
||||
|
||||
<!-- useHttp Example -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { useHttp } from '@inertiajs/vue3'
|
||||
|
||||
const http = useHttp({
|
||||
query: '',
|
||||
})
|
||||
|
||||
function search() {
|
||||
http.get('/api/search', {
|
||||
onSuccess: (response) => {
|
||||
console.log(response)
|
||||
},
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input v-model="http.query" @input="search" />
|
||||
<div v-if="http.processing">Searching...</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Optimistic Updates
|
||||
|
||||
Apply data changes instantly before the server responds, with automatic rollback on failure:
|
||||
|
||||
<!-- Optimistic Update with Router -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { router } from '@inertiajs/vue3'
|
||||
|
||||
function like(post) {
|
||||
router.optimistic((props) => ({
|
||||
post: {
|
||||
...props.post,
|
||||
likes: props.post.likes + 1,
|
||||
},
|
||||
})).post(`/posts/${post.id}/like`)
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
Optimistic updates also work with `useForm` and the `<Form>` component:
|
||||
|
||||
<!-- Optimistic Update with Form Component -->
|
||||
```vue
|
||||
<template>
|
||||
<Form
|
||||
action="/todos"
|
||||
method="post"
|
||||
:optimistic="(props, data) => ({
|
||||
todos: [...props.todos, { id: Date.now(), name: data.name, done: false }],
|
||||
})"
|
||||
>
|
||||
<input type="text" name="name" />
|
||||
<button type="submit">Add Todo</button>
|
||||
</Form>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Instant Visits
|
||||
|
||||
Navigate to a new page immediately without waiting for the server response. The target component renders right away with shared props, while page-specific props load in the background.
|
||||
|
||||
<!-- Instant Visit with Link -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { Link } from '@inertiajs/vue3'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Link href="/dashboard" component="Dashboard">Dashboard</Link>
|
||||
|
||||
<Link
|
||||
href="/posts/1"
|
||||
component="Posts/Show"
|
||||
:page-props="{ post: { id: 1, title: 'My Post' } }"
|
||||
>
|
||||
View Post
|
||||
</Link>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Layout Props
|
||||
|
||||
Share dynamic data between pages and persistent layouts:
|
||||
|
||||
<!-- Layout Props in Layout -->
|
||||
```vue
|
||||
<script setup>
|
||||
withDefaults(defineProps({
|
||||
title: String,
|
||||
showSidebar: Boolean,
|
||||
}), {
|
||||
title: 'My App',
|
||||
showSidebar: true,
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<header>{{ title }}</header>
|
||||
<aside v-if="showSidebar">Sidebar</aside>
|
||||
<main>
|
||||
<slot />
|
||||
</main>
|
||||
</template>
|
||||
```
|
||||
|
||||
<!-- Setting Layout Props from Page -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { setLayoutProps } from '@inertiajs/vue3'
|
||||
|
||||
setLayoutProps({
|
||||
title: 'Dashboard',
|
||||
showSidebar: false,
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<h1>Dashboard</h1>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Deferred Props
|
||||
|
||||
Use deferred props to load data after initial page render:
|
||||
|
||||
<!-- Deferred Props with Empty State -->
|
||||
```vue
|
||||
<script setup>
|
||||
defineProps({
|
||||
users: Array
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<h1>Users</h1>
|
||||
<div v-if="!users" class="animate-pulse">
|
||||
<div class="h-4 bg-gray-200 rounded w-3/4 mb-2"></div>
|
||||
<div class="h-4 bg-gray-200 rounded w-1/2"></div>
|
||||
</div>
|
||||
<ul v-else>
|
||||
<li v-for="user in users" :key="user.id">
|
||||
{{ user.name }}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Polling
|
||||
|
||||
Use the `usePoll` composable to automatically refresh data at intervals. It handles cleanup on unmount and throttles polling when the tab is inactive.
|
||||
|
||||
<!-- Basic Polling -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { usePoll } from '@inertiajs/vue3'
|
||||
|
||||
defineProps({
|
||||
stats: Object
|
||||
})
|
||||
|
||||
usePoll(5000)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<h1>Dashboard</h1>
|
||||
<div>Active Users: {{ stats.activeUsers }}</div>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
<!-- Polling With Request Options and Manual Control -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { usePoll } from '@inertiajs/vue3'
|
||||
|
||||
defineProps({
|
||||
stats: Object
|
||||
})
|
||||
|
||||
const { start, stop } = usePoll(5000, {
|
||||
only: ['stats'],
|
||||
onStart() {
|
||||
console.log('Polling request started')
|
||||
},
|
||||
onFinish() {
|
||||
console.log('Polling request finished')
|
||||
},
|
||||
}, {
|
||||
autoStart: false,
|
||||
keepAlive: true,
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<h1>Dashboard</h1>
|
||||
<div>Active Users: {{ stats.activeUsers }}</div>
|
||||
<button @click="start">Start Polling</button>
|
||||
<button @click="stop">Stop Polling</button>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
- `autoStart` (default `true`) - set to `false` to start polling manually via the returned `start()` function
|
||||
- `keepAlive` (default `false`) - set to `true` to prevent throttling when the browser tab is inactive
|
||||
|
||||
### WhenVisible
|
||||
|
||||
Lazy-load a prop when an element scrolls into view. Useful for deferring expensive data that sits below the fold:
|
||||
|
||||
<!-- WhenVisible Example -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { WhenVisible } from '@inertiajs/vue3'
|
||||
|
||||
defineProps({
|
||||
stats: Object
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<h1>Dashboard</h1>
|
||||
|
||||
<WhenVisible data="stats" :buffer="200">
|
||||
<template #fallback>
|
||||
<div class="animate-pulse">Loading stats...</div>
|
||||
</template>
|
||||
|
||||
<template #default="{ fetching }">
|
||||
<div>
|
||||
<p>Total Users: {{ stats.total_users }}</p>
|
||||
<p>Revenue: {{ stats.revenue }}</p>
|
||||
<span v-if="fetching">Refreshing...</span>
|
||||
</div>
|
||||
</template>
|
||||
</WhenVisible>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
### InfiniteScroll
|
||||
|
||||
Automatically load additional pages of paginated data as users scroll:
|
||||
|
||||
<!-- InfiniteScroll Example -->
|
||||
```vue
|
||||
<script setup>
|
||||
import { InfiniteScroll } from '@inertiajs/vue3'
|
||||
|
||||
defineProps({
|
||||
users: Object
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<InfiniteScroll data="users">
|
||||
<div v-for="user in users.data" :key="user.id">
|
||||
{{ user.name }}
|
||||
</div>
|
||||
</InfiniteScroll>
|
||||
</template>
|
||||
```
|
||||
|
||||
The server must use `Inertia::scroll()` to configure the paginated data. Use the `search-docs` tool with a query of `infinite scroll` for detailed guidance on buffers, manual loading, reverse mode, and custom trigger elements.
|
||||
|
||||
## Server-Side Patterns
|
||||
|
||||
Server-side patterns (Inertia::render, props, middleware) are covered in inertia-laravel guidelines.
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
- Using traditional `<a>` links instead of Inertia's `<Link>` component (breaks SPA behavior)
|
||||
- Forgetting that Vue components must have a single root element
|
||||
- Forgetting to add loading states (skeleton screens) when using deferred props
|
||||
- Not handling the `undefined` state of deferred props before data loads
|
||||
- Using `<form>` without preventing default submission (use `<Form>` component or `@submit.prevent`)
|
||||
- Forgetting to check if `<Form>` component is available in your Inertia version
|
||||
- Using `router.cancel()` instead of `router.cancelAll()` (v3 breaking change)
|
||||
- Using `router.on('invalid', ...)` or `router.on('exception', ...)` instead of the renamed `httpException` and `networkError` events
|
||||
|
|
@ -1,104 +0,0 @@
|
|||
---
|
||||
name: infer-conventions
|
||||
description: "Use this skill to analyze how a Laravel application is actually written and record its conventions as shared rules. Trigger when the user wants to detect, infer, document, or standardize project conventions or coding style, set up or grow `.ai/rules`, resolve mixed or conflicting patterns (e.g. \"are we using Form Requests or inline validation?\"), or onboard agents and teammates to \"how we do things here\". Covers: a systematic sweep of ~49 Laravel convention dimensions (validation, models, architecture, testing, frontend, database, console), open-ended house-pattern discovery, conflict reporting, and recording rules scoped to the right paths via the Boost `record-rule` MCP tool. Do not use for one-off code review, enforcing formatting a linter already handles, or editing `.ai/rules` files by hand."
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
|
||||
# Infer Conventions
|
||||
|
||||
Learn how this application writes Laravel, then record what you learn as durable, path-scoped rules other agents will read. You are documenting reality, not improving it.
|
||||
|
||||
## Ground Rules (read before you start)
|
||||
|
||||
- Consistency first. The codebase's majority style is the convention. Never judge it, never propose a "better" pattern, never record what the code should do. If the app validates inline everywhere, that is the rule, even if Form Requests would be nicer.
|
||||
- Skip what an active tool produces, keep what a tool would fight. Inspect the project's Pint and Rector configuration first; a Rector transformation is tooling-owned only when its package and relevant rule or set are installed and enabled. Active tools may rewrite code toward one canonical form: `$casts` to `casts()`, `$fillable` to attributes, magic accessors to the `Attribute` class, pipe-string rules to arrays, `$signature` to `#[Signature]`, named migrations to anonymous, and many more. When the app already sits at an active tool's target form, the tool owns it, so record nothing. But when the app deliberately holds a form an active tool would refactor away, such as legacy `getXxxAttribute()` accessors the `Attribute` class would replace, no tool can reproduce that choice and an agent defaults the other way. That against-the-grain hold is exactly what to record.
|
||||
- Record decisions, not defaults. A consistent pattern earns a rule only when it reflects a choice: the app took one valid option where the framework or common practice offered others, or the pattern would surprise a competent agent. Framework defaults steer nothing, so skip them: anonymous migrations, `$signature` commands, `ShouldQueue` jobs, `casts()` on Laravel 11+, named routes, Rule objects in `app/Rules`, and `Mail::fake()` or `Bus::fake()` to isolate framework services. A real fork is not enough on its own. Weigh the side the app took, and record only the side an agent would not reach for by itself: inline closures everywhere, legacy accessors, a bespoke query layer. Watch for the false fork too. "No Mockery" next to facade fakes is not a choice against Mockery, because they double different things. The test for every candidate: without this rule, would the next agent plausibly write it differently? Only "yes" earns a rule.
|
||||
- Architecture choices are the gold. Record presence and deliberate absence. The structural pattern the app commits to is the highest-signal convention and the one no tool can decide: Action classes and how they are invoked (`handle` / `execute` / `__invoke`), service objects, dedicated query objects exposing `builder()`, DTOs (spatie/laravel-data vs readonly classes), Form Request validation vs inline, an events and listeners spine vs direct calls, and domain or module folders. Also record a consistent non-pattern, such as "query Eloquent directly in controllers, no repository layer", so the next agent matches the app's altitude instead of over-engineering.
|
||||
- Never duplicate `.ai/rules`. Read `.ai/rules/index.md` and the area files before the sweep. A dimension already covered there is marked done and skipped.
|
||||
- Evidence or silence. A convention needs at least 3 consistent examples and no meaningful rival to become a candidate. Every Step 1 verdict applies this bar.
|
||||
- The recorded rule states the convention, nothing else. One or two imperative lines: this project does X, so do X here. Keep detection evidence out. No counts, ratios, current usage, file lists, or example paths, because that is proof for the confirm step, not part of the rule. One short syntax fragment at most, and point to `search-docs` for API details.
|
||||
|
||||
## Process
|
||||
|
||||
Each step ends on a checkable completion criterion. Do not advance until it holds.
|
||||
|
||||
Fan out when you can. The sweep is embarrassingly parallel. If your environment can spawn subagents (a Task, dispatch, or equivalent tool), do Step 0 yourself, then hand each checklist group (A to J) and the architecture map to its own subagent. Each subagent runs the greps, reads a few representative files, and returns structured verdicts (dimension, verdict, evidence, proposed glob / title / note). You aggregate, dedupe, then run Steps 3 to 5. It is far faster on a real app. No subagents available? Run the steps in sequence, with the same bar and the same output.
|
||||
|
||||
### Step 0: Orient
|
||||
|
||||
Read `composer.json` (installed packages tell you which checklist groups apply), the `pint.json` / PHPStan / Rector config, `.ai/rules/index.md` if present, and most important, map the `app/` tree. List every directory under `app/` (and any `Modules/`, `src/`, `packages/`, or domain root). Every folder beyond Laravel's default skeleton (`Http`, `Models`, `Providers`, `Console`, `Exceptions`) is a structural pattern the app committed to and a high-value rule waiting to be written: `Actions`, `Services`, `Data` or DTOs, `Queries`, `Repositories`, `ViewModels`, `Pipelines`, `Support`, `Enums`, `Contracts`, `Observers`, or `Domain` and module roots. Note each one. You will confirm how it is used in Step 2.
|
||||
|
||||
This app ships a frontend stack, so the frontend checklist group applies. Sweep it.
|
||||
|
||||
Done when: you have the applicable checklist groups, the dimensions already recorded in `.ai/rules`, and a list of every non-default `app/` directory mapped to the pattern it represents.
|
||||
|
||||
### Step 1: Predefined sweep
|
||||
|
||||
Open `references/checklist.md` and work every applicable dimension using its search hints. Give each exactly one verdict:
|
||||
|
||||
- Pattern. Clears the bar, rival under ~20% of sites, and reflects a real choice (passes the decisions-not-defaults test). A recording candidate. Cite 2 to 3 example files.
|
||||
- Conflict. Both styles present in meaningful numbers. Report the split with counts and example files. Never record a preferred winner while the code remains mixed, even in yolo, because that would describe an aspiration rather than reality. Record only if the user identifies a stable path or context boundary that explains both styles; otherwise defer until the code is reconciled.
|
||||
- Default. Consistent, but a framework or common-practice default the agent already writes unprompted. Skip it as a no-op, not a convention.
|
||||
- No signal. Under the bar: feature unused, or too few examples. Skip silently (one summary line at most).
|
||||
- Tooling-owned or Already-recorded. Skip per the ground rules.
|
||||
|
||||
Done when: every applicable dimension carries exactly one of those verdicts.
|
||||
|
||||
### Step 2: Open-ended pass
|
||||
|
||||
First, close out the architecture map from Step 0. For every non-default `app/` directory you listed, confirm how the pattern is used and apply the same evidence and decisions-not-defaults tests as Step 1. Generator-standard or sparsely used directories such as `Rules`, `Observers`, `Mail`, and `Notifications` are signals to inspect, not automatic conventions. Make genuine structural patterns candidates: Action classes invoked via `handle` / `execute` / `__invoke`, Services constructor-injected, `Queries` objects exposing `builder(): Builder`, DTOs as readonly classes or spatie/laravel-data, module or domain folders as the unit of organization. Scope each qualifying pattern to its own directory glob. Also record a consistent deliberate absence, such as "no repository layer, controllers query Eloquent directly", so the next agent matches the app's altitude.
|
||||
|
||||
Then find what else makes this codebase itself: base or abstract classes most code extends, traits used everywhere, tenancy or authorization scoping woven through queries, naming schemes, and custom helpers. Same evidence bar, cite files. Record every genuine structural pattern, and cap the other house findings at ~5 so the pass stays high-signal.
|
||||
|
||||
Done when: every non-default `app/` directory from Step 0 has a verdict, and the pass has produced its cited house findings (or concluded there are none).
|
||||
|
||||
### Step 3: Confirm
|
||||
|
||||
Present every candidate in one batch. Per item: dimension, verdict, evidence (counts and files), and the exact proposed `glob` or `globs` / `title` / `note`. Conflicts are presented as questions about an existing context boundary or deferred cleanup, not as a choice of future style.
|
||||
|
||||
Default mode is confirm: record only what the user approves. Switch to yolo only when the invocation said so ("yolo", "don't ask", "just record them"), then record all pattern candidates without asking. Conflicts still go to the user in yolo.
|
||||
|
||||
Done when: every candidate is approved, rejected, or (conflicts) decided.
|
||||
|
||||
### Step 4: Record
|
||||
|
||||
Make one `record-rule` call for each glob an approved convention applies to. Choose the most specific globs that cover the cited evidence from the mapping table below; if a convention spans models and migrations, record it under both domains so agents discover it from either path. The `note` is the bare convention: strip every trace of detection (see the ground rule). If `record-rule` is unavailable (rules disabled), report the full rule text so the user can enable `BOOST_RULES_ENABLED` or add it by hand.
|
||||
|
||||
Record this:
|
||||
|
||||
> Accessors and mutators: use the legacy magic-method style (`getXxxAttribute()` / `setXxxAttribute()`), not the `Attribute` class. Match it in models.
|
||||
|
||||
Not this:
|
||||
|
||||
> Accessors/mutators use the legacy magic-method style; the `Attribute`-class style is not used anywhere (13 legacy, 0 Attribute-class), e.g. `app/Models/Post.php`. Match the legacy style in existing models.
|
||||
|
||||
Done when: every approved item has a successful tool response, and any failure is reported with its rule text.
|
||||
|
||||
### Step 5: Summarize
|
||||
|
||||
List recorded rules (file and title), conflicts the user deferred, notable no-signals, and remind the user to commit `.ai/rules` so their team and agents share the conventions.
|
||||
|
||||
## Glob mapping
|
||||
|
||||
Attach each rule to the most specific path that covers its evidence. Never a lazy `app/**` when a subtree fits. Match the glob to where the code actually lives, which is not the same in a default skeleton and in a modular or DDD layout. Use the Step 0 `app/` map to pick the real path.
|
||||
|
||||
Examples:
|
||||
|
||||
- Models: `app/Models/**` in a default app, or `app/Modules/Blog/Models/**` / `src/Domain/Blog/**` in a modular one.
|
||||
- Controllers, routing, validation, responses: `app/Http/**`, or `app/Modules/*/Http/**` when each module owns its HTTP layer.
|
||||
- Actions, Services, DTOs: `app/Actions/**`, `app/Services/**`, `app/Data/**`, or the module path the app actually uses.
|
||||
- Tests: `tests/**`.
|
||||
- Migrations and database: `database/migrations/**`.
|
||||
- Truly app-wide (rare, e.g. auth retrieval): `app/**`.
|
||||
|
||||
`record-rule` takes one glob. When a convention genuinely spans two domains (e.g. UUID keys touch models and migrations), call it once per domain with the same title and note; mentioning another path in the note does not make the rule discoverable there.
|
||||
|
||||
## Edge cases
|
||||
|
||||
- Rules disabled or `record-rule` missing: detection is read-only, so Steps 0 to 3 still run, and recording falls back to the manual path in Step 4.
|
||||
- Tiny or fresh app: most dimensions land on no-signal. Say so honestly ("not enough code to infer conventions yet") and record nothing.
|
||||
- Huge app: each dimension is a bounded grep plus a handful of file reads. Sample representative files, do not read everything.
|
||||
- Re-runs: reading `.ai/rules` in Step 0 makes re-runs incremental, so only new or undecided dimensions surface.
|
||||
- Non-standard layout (modules, DDD): the open-ended pass catches the layout itself as convention #1. Adapt the globs in the mapping table to the observed paths.
|
||||
|
|
@ -1,137 +0,0 @@
|
|||
# Detection Checklist
|
||||
|
||||
Every dimension here is a genuine fork: Laravel offers two or more valid approaches, the app's choice changes what the next agent writes, and no active project tool can pick for you. Left out on purpose: pure formatting (Pint owns it), any form an installed and enabled Rector rule rewrites to one canonical shape (`$casts` to `casts()`, `$fillable` to attributes, pipe-string rules to arrays, named to anonymous migrations, `$signature` to `#[Signature]`), and framework defaults any agent writes unprompted (`ShouldQueue` jobs, relation return types, `HasFactory`).
|
||||
|
||||
Each item gives the fork, then a hint (a grep or dir to spot which side the app takes). Hints are only a start. Read the matched files, never record on a raw count. Apply the ground rules to every verdict: a consistent choice that is a default or a tool's target form is not a pattern. Rows tagged (architecture) are the highest-signal, so record presence and deliberate absence.
|
||||
|
||||
---
|
||||
|
||||
## A. Validation & HTTP input
|
||||
|
||||
1. Validation entry point: inline `$request->validate()` vs Form Request classes vs `Validator::make()`.
|
||||
- Hint: `ls app/Http/Requests`; grep `->validate(` / `Validator::make(` in `app/Http/Controllers`.
|
||||
2. Custom rule location: invokable rule objects in `app/Rules` vs inline closures vs `Validator::extend()` in a provider. Rule objects are the default `make:rule` path, so record only if the app leans on closures or `Validator::extend` instead. "No rule objects" alone is just no-signal.
|
||||
- Hint: `ls app/Rules`; grep `Validator::extend` in `app/Providers`.
|
||||
3. Typed input retrieval: typed getters (`$request->string()`, `->integer()`, `->enum()`, `->date()`) vs raw `$request->input()` / dynamic properties.
|
||||
- Hint: grep `->string(` / `->integer(` / `->enum(` vs `->input(` in `app/Http`.
|
||||
4. Custom messages/attributes: `lang/*/validation.php` vs Form Request `messages()` / `attributes()` methods.
|
||||
- Hint: `ls lang`; grep `function messages`, `function attributes` in `app/Http/Requests`.
|
||||
|
||||
## B. Controllers & routing
|
||||
|
||||
5. Controller shape: invokable single-action (`__invoke`) vs resource controllers vs plain multi-method.
|
||||
- Hint: grep `__invoke` in controllers; `Route::resource` / `apiResource` vs verb routes.
|
||||
6. Business-logic location (architecture): fat controllers vs delegated to Actions / Services / Jobs.
|
||||
- Hint: read a few controller methods; `ls app/Actions app/Services`.
|
||||
7. Route handler style: closures in `routes/*.php` vs controller classes.
|
||||
- Hint: count `function ()` vs `::class` in `routes/web.php`, `routes/api.php`.
|
||||
8. Middleware assignment: route/group `->middleware()` vs controller `HasMiddleware::middleware()` vs `#[Middleware]` attribute.
|
||||
- Hint: grep `implements HasMiddleware`, `#[Middleware(` in controllers vs `->middleware(` in routes.
|
||||
9. Route model binding: implicit (type-hinted models) vs explicit `Route::bind` vs manual `findOrFail`.
|
||||
- Hint: typed model params in signatures vs `findOrFail(` in controllers; grep `Route::bind`.
|
||||
10. Rate limiting: named `RateLimiter::for()` + `throttle:name` vs inline `throttle:60,1`.
|
||||
- Hint: grep `RateLimiter::for` in providers vs `throttle:` in route files.
|
||||
|
||||
## C. Authorization
|
||||
|
||||
11. Authorization home: Gates (`Gate::define`) vs Policy classes in `app/Policies`.
|
||||
- Hint: `ls app/Policies`; grep `Gate::define` in `app/Providers`.
|
||||
12. Authorization call site: `$this->authorize()` / `Gate::authorize()` vs `$user->can()` vs `can` middleware vs `#[Authorize]` vs `@can` in Blade.
|
||||
- Hint: grep `authorize(`, `->can(`, `middleware('can:`, `#[Authorize(`, `@can(`.
|
||||
|
||||
## D. Eloquent & models
|
||||
|
||||
13. Mass assignment: `$fillable` allow-list vs `$guarded` block-list.
|
||||
- Hint: grep `protected $fillable` / `protected $guarded` in `app/Models`.
|
||||
14. Accessors/mutators: modern `Attribute` class vs legacy `getXxxAttribute()` / `setXxxAttribute()`. Record a legacy hold, it goes against the tool's grain.
|
||||
- Hint: grep `: Attribute` / `Attribute::make` vs `function get[A-Z].*Attribute` in `app/Models`.
|
||||
15. Primary keys: auto-increment vs `HasUuids` vs `HasUlids`.
|
||||
- Hint: grep `HasUuids` / `HasUlids` in `app/Models`; migration `id()` vs `uuid('id')`.
|
||||
16. Custom casts: dedicated `CastsAttributes` classes (`app/Casts`) vs inline `Attribute` vs built-in cast strings.
|
||||
- Hint: `ls app/Casts`; grep `Cast::class`, `AsStringable::class` in models.
|
||||
17. Data/query layer (architecture): Eloquent directly in controllers vs repositories vs dedicated query objects (e.g. classes exposing `builder(): Builder`).
|
||||
- Hint: `ls app/Repositories app/Queries`; see where non-trivial queries are built.
|
||||
18. Query scopes: local `scope`/`#[Scope]` methods vs dedicated builder classes.
|
||||
- Hint: grep `function scope` / `#[Scope]` in models; `ls app/*/Builders`.
|
||||
19. Model events: observers (`app/Observers`, `#[ObservedBy]`) vs `booted()` closures vs event classes.
|
||||
- Hint: `ls app/Observers`; grep `booted`, `::observe`, `#[ObservedBy]`.
|
||||
20. Eager-load posture: explicit per-query `->with()` vs model-level `$with` defaults. Treat `preventLazyLoading()` separately as a development guard because it can complement either posture.
|
||||
- Hint: grep `protected $with`, `->with(`, and separately `preventLazyLoading` in `app/`.
|
||||
|
||||
## E. Architecture & organization
|
||||
|
||||
21. Action/Service structure (architecture): Action classes (invoked via `handle` / `execute` / `__invoke`) vs service objects vs neither. Cross-check the Step 0 `app/` map: any `Actions`/`Services`/`Pipelines`/`Jobs`-as-actions folder is this pattern, so record how it is invoked.
|
||||
- Hint: `ls app/` (the whole tree, not just `Actions`/`Services`); grep the invocation method in the folder you find.
|
||||
22. DTOs (architecture): spatie/laravel-data vs plain readonly classes vs arrays everywhere.
|
||||
- Hint: `ls app/Data`; grep `extends Data`, `readonly class` in `app/`.
|
||||
23. Dependency acquisition: constructor/method injection vs `app()` / `resolve()` / `App::make()` service location.
|
||||
- Hint: grep `app(` / `resolve(` / `::make(` in `app/` vs promoted constructor deps.
|
||||
24. Decoupling: events + listeners vs direct service calls.
|
||||
- Hint: `ls app/Events app/Listeners`; grep `event(`, `::dispatch(`.
|
||||
25. Helper vs facade idiom: global helpers (`config()`, `auth()`, `response()`) vs facades (`Config::`, `Auth::`, `Response::`).
|
||||
- Hint: ratio of `config(` vs `Config::` (etc.) across `app/`.
|
||||
26. Namespace layout (architecture): default `app/` skeleton vs domain/module folders (`app/Domain/**`, modules).
|
||||
- Hint: `ls app/`, look for `Domain/`, `Modules/`, bounded-context folders.
|
||||
27. Enums: backed vs pure; case naming; where they live.
|
||||
- Hint: `ls app/Enums`; grep `enum .*: string`, `enum .*: int`.
|
||||
|
||||
## F. Frontend & views
|
||||
|
||||
This app ships a frontend stack, so the items below apply.
|
||||
|
||||
28. Frontend stack: Blade+Livewire vs Inertia (Vue/React/Svelte) vs Blade-only / API + separate SPA.
|
||||
- Hint: `composer.json` + `package.json`; `ls resources/js/pages`, `resources/views`.
|
||||
29. Blade composition: class `<x-*>` components vs anonymous components (`@props`) vs `@include` partials.
|
||||
- Hint: `ls app/View/Components`; grep `<x-`, `@include` in `resources/views`.
|
||||
32. Localization: short keys (`lang/*/*.php` + `__('messages.welcome')`) vs JSON string keys (`lang/*.json` + `__('Full sentence')`).
|
||||
- Hint: `ls lang`; grep dotted `__('` vs sentence keys.
|
||||
|
||||
## G. Database & migrations
|
||||
|
||||
33. Foreign keys: `foreignId()->constrained()` vs `foreignIdFor(Model::class)` vs manual `foreign()->references()->on()`.
|
||||
- Hint: grep `foreignId(`, `foreignIdFor(`, `->foreign(` in `database/migrations`.
|
||||
34. `down()` methods: real reverse logic vs omitted / one-way migrations.
|
||||
- Hint: grep `function down` vs the migration count.
|
||||
35. Enum storage: DB `enum()` column vs `string()` + PHP-enum cast on the model.
|
||||
- Hint: grep `->enum(` in migrations vs string columns cast to enums.
|
||||
36. Transactions: `DB::transaction(fn ...)` closure vs manual `beginTransaction` / `commit` / `rollBack`.
|
||||
- Hint: grep `DB::transaction`, `beginTransaction` in `app/`.
|
||||
37. Idempotent writes: `upsert` / `updateOrCreate` / `firstOrCreate` vs find-then-save.
|
||||
- Hint: grep `upsert(`, `updateOrCreate(`, `firstOrCreate(` in `app/`.
|
||||
|
||||
## H. Testing
|
||||
|
||||
38. Framework: Pest (`it()` / `test()` / `expect()`) vs PHPUnit classes.
|
||||
- Hint: `ls tests/Pest.php`; grep `it(` / `test(` vs `extends TestCase`.
|
||||
39. DB reset: `RefreshDatabase` vs `DatabaseTruncation` vs `DatabaseMigrations`.
|
||||
- Hint: grep those trait names in `tests/`.
|
||||
40. Fixtures: compare how equivalent test-owned records are created, such as factories vs manual inserts. Track seeders separately for shared reference data because `$this->seed()` commonly and legitimately coexists with factories.
|
||||
- Hint: grep `::factory(` and direct inserts in `tests/`; separately inspect `$this->seed(` calls and what those seeders provide.
|
||||
41. Collaborator isolation: how the app doubles its own classes, Mockery `mock()` / `spy()` vs real integration. Ignore facade fakes like `Mail::fake()` here, they isolate framework services by default and are not a fork against Mockery.
|
||||
- Hint: grep `->mock(`, `->spy(`, `Mockery::` in `tests/`.
|
||||
42. Endpoint assertions: array `assertJson([...])` / `assertJsonFragment` vs fluent `AssertableJson`.
|
||||
- Hint: grep `AssertableJson`, `assertJsonFragment` in `tests/`.
|
||||
|
||||
## I. Responses & API resources
|
||||
|
||||
43. Response shape: API Resource classes vs `response()->json()` vs returning models/arrays directly.
|
||||
- Hint: `ls app/Http/Resources`; grep `JsonResource`, `->json(` in controllers.
|
||||
44. Resource relationship inclusion: `whenLoaded()` guards vs unconditional relationship access. Do not count ordinary scalar attributes as rivals to conditional relationships, and evaluate general `when()` fields separately.
|
||||
- Hint: compare relationship fields using `whenLoaded(` with unconditional relationship property access in `app/Http/Resources`.
|
||||
45. Pagination contracts: within comparable endpoint categories, length-aware `paginate()` vs `simplePaginate()` vs `cursorPaginate()`. These have different totals, navigation, ordering, and performance contracts, so record only a stable path-scoped API policy, never a project-wide majority.
|
||||
- Hint: grep those in `app/`, then group matches by endpoint type and client contract before comparing them.
|
||||
46. Web redirects/URLs: `route('name')` vs `url('/path')` vs `action([...])`.
|
||||
- Hint: grep `route('`, `url('/`, `action([` in `app/Http` and views.
|
||||
|
||||
## J. Strings, collections & dates
|
||||
|
||||
47. Iteration idiom: `collect()->map()->filter()` pipelines vs `array_map` / `foreach`.
|
||||
- Hint: grep `collect(`, `->map(` vs `array_map`, `foreach` density in `app/`.
|
||||
48. String API: fluent `Str::of()->...` (Stringable) vs static `Str::` vs native (`trim`, `strtoupper`).
|
||||
- Hint: grep `Str::of(` vs `Str::` vs native string funcs.
|
||||
49. Dates: compare equivalent construction call styles (`now()` / `today()` helpers vs `Carbon::`) separately from the application's mutable/immutable date policy. `Date::use(CarbonImmutable::class)` can make helpers return immutable dates, so those signals are complementary rather than conflicting.
|
||||
- Hint: grep `now(` and `Carbon::` for call style; separately inspect `CarbonImmutable` and `Date::use` for mutability policy.
|
||||
|
||||
---
|
||||
|
||||
Genuine forks only. Every row survived the "no tool can decide this, and it isn't the default" filter. Give each applicable dimension exactly one verdict: pattern, conflict, default, no-signal, tooling-owned, or already-recorded. The rows tagged (architecture) are where the highest-value rules come from.
|
||||
|
|
@ -1,59 +0,0 @@
|
|||
---
|
||||
name: laravel-best-practices
|
||||
description: "Apply this skill whenever writing, reviewing, or refactoring Laravel PHP code. This includes creating or modifying controllers, models, migrations, form requests, policies, jobs, scheduled commands, service classes, and Eloquent queries. Triggers for N+1 and query performance issues, caching strategies, authorization and security patterns, validation, error handling, queue and job configuration, route definitions, and architectural decisions. Also use for Laravel code reviews and refactoring existing Laravel code to follow best practices. Covers any task involving Laravel backend PHP code patterns."
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
|
||||
# Laravel Best Practices
|
||||
|
||||
Best practices for Laravel, organized as an index of rule files. Each rule file teaches what to do and why. For exact API syntax, verify with `search-docs`.
|
||||
|
||||
## Consistency First
|
||||
|
||||
Before applying any rule, check what the application already does. Laravel offers multiple valid approaches, and the best choice is the one the codebase already uses, even if another pattern would be theoretically better. Inconsistency is worse than a suboptimal pattern.
|
||||
|
||||
Check sibling files, related controllers, models, or tests for established patterns. If one exists, follow it. Don't introduce a second way. These rules are defaults for when no pattern exists yet, not overrides.
|
||||
|
||||
## How to Apply
|
||||
|
||||
1. Check the changed files, nearby code, project configuration, and relevant tests for established patterns. Deviate only for a correctness or security defect, and call the deviation out.
|
||||
2. Map every affected concern to the rule index below. Read each mapped rule file before editing. Skip unrelated rule files.
|
||||
3. Make the smallest coherent change. Keep the application's architecture and naming instead of introducing a second pattern for the same job.
|
||||
4. Verify version-sensitive Laravel APIs for the installed version with `search-docs`, or inspect the installed framework when it is unavailable.
|
||||
5. Run the narrowest relevant tests first, then the project's formatting and static-analysis checks when the change warrants them.
|
||||
6. Re-read the diff against every mapped rule before finishing.
|
||||
|
||||
## Rule Index
|
||||
|
||||
Cross-cutting changes often need more than one rule file.
|
||||
|
||||
| Concern | Read |
|
||||
| --- | --- |
|
||||
| Query count, eager loading, indexes, large datasets | [`rules/db-performance.md`](rules/db-performance.md) |
|
||||
| Subqueries, aggregates, complex ordering and query plans | [`rules/advanced-queries.md`](rules/advanced-queries.md) |
|
||||
| Models, relationships, scopes, casts | [`rules/eloquent.md`](rules/eloquent.md) |
|
||||
| Authentication, authorization, input safety, secrets, uploads | [`rules/security.md`](rules/security.md) |
|
||||
| Form Requests and validation rules | [`rules/validation.md`](rules/validation.md) |
|
||||
| Controllers, route binding, resources, middleware | [`rules/routing.md`](rules/routing.md) |
|
||||
| Schema changes, columns, foreign keys, indexes | [`rules/migrations.md`](rules/migrations.md) |
|
||||
| Jobs, retries, uniqueness, batches, Horizon | [`rules/queue-jobs.md`](rules/queue-jobs.md) |
|
||||
| Cache lifetime, invalidation, locks, memoization | [`rules/caching.md`](rules/caching.md) |
|
||||
| Outbound requests, retries, timeouts, fakes | [`rules/http-client.md`](rules/http-client.md) |
|
||||
| Exceptions, reporting, rendering, log context | [`rules/error-handling.md`](rules/error-handling.md) |
|
||||
| Events and notifications | [`rules/events-notifications.md`](rules/events-notifications.md) |
|
||||
| Mailables and mail assertions | [`rules/mail.md`](rules/mail.md) |
|
||||
| Scheduled tasks and overlap protection | [`rules/scheduling.md`](rules/scheduling.md) |
|
||||
| Collections, lazy iteration, bulk operations | [`rules/collections.md`](rules/collections.md) |
|
||||
| Blade components, attributes, composers | [`rules/blade-views.md`](rules/blade-views.md) |
|
||||
| Environment values and application configuration | [`rules/config.md`](rules/config.md) |
|
||||
| Pest/PHPUnit patterns, factories, fakes | [`rules/testing.md`](rules/testing.md) |
|
||||
| Naming, helpers, file boundaries, PHP style | [`rules/style.md`](rules/style.md) |
|
||||
| Actions, services, dependencies, application structure | [`rules/architecture.md`](rules/architecture.md) |
|
||||
|
||||
## Decision Rules
|
||||
|
||||
- Prefer framework features and existing application abstractions over new helpers or dependencies.
|
||||
- Avoid speculative abstractions. Extract code when it creates a clear domain boundary, removes meaningful duplication, or makes behavior independently testable.
|
||||
- Keep database access out of Blade views and prevent hidden N+1 queries across controllers, resources, jobs, and serialization.
|
||||
|
|
@ -1,106 +0,0 @@
|
|||
# Advanced Query Patterns
|
||||
|
||||
## Use `addSelect()` Subqueries for Single Values from Has-Many
|
||||
|
||||
Instead of eager-loading an entire has-many relationship for a single value (like the latest timestamp), use a correlated subquery via `addSelect()`. This pulls the value directly in the main SQL query — zero extra queries.
|
||||
|
||||
```php
|
||||
public function scopeWithLastLoginAt($query): void
|
||||
{
|
||||
$query->addSelect([
|
||||
'last_login_at' => Login::select('created_at')
|
||||
->whereColumn('user_id', 'users.id')
|
||||
->latest()
|
||||
->take(1),
|
||||
])->withCasts(['last_login_at' => 'datetime']);
|
||||
}
|
||||
```
|
||||
|
||||
## Create Dynamic Relationships via Subquery FK
|
||||
|
||||
Extend the `addSelect()` pattern to fetch a foreign key via subquery, then define a `belongsTo` relationship on that virtual attribute. This provides a fully-hydrated related model without loading the entire collection.
|
||||
|
||||
```php
|
||||
public function lastLogin(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Login::class);
|
||||
}
|
||||
|
||||
public function scopeWithLastLogin($query): void
|
||||
{
|
||||
$query->addSelect([
|
||||
'last_login_id' => Login::select('id')
|
||||
->whereColumn('user_id', 'users.id')
|
||||
->latest()
|
||||
->take(1),
|
||||
])->with('lastLogin');
|
||||
}
|
||||
```
|
||||
|
||||
## Use Conditional Aggregates Instead of Multiple Count Queries
|
||||
|
||||
Replace N separate `count()` queries with a single query using `CASE WHEN` inside `selectRaw()`. Use `toBase()` to skip model hydration when you only need scalar values.
|
||||
|
||||
```php
|
||||
$statuses = Feature::toBase()
|
||||
->selectRaw("count(case when status = 'Requested' then 1 end) as requested")
|
||||
->selectRaw("count(case when status = 'Planned' then 1 end) as planned")
|
||||
->selectRaw("count(case when status = 'Completed' then 1 end) as completed")
|
||||
->first();
|
||||
```
|
||||
|
||||
## Use `setRelation()` to Prevent Circular N+1
|
||||
|
||||
When a parent model is eager-loaded with its children, and the view also needs `$child->parent`, use `setRelation()` to inject the already-loaded parent rather than letting Eloquent fire N additional queries.
|
||||
|
||||
```php
|
||||
$feature->load('comments.user');
|
||||
$feature->comments->each->setRelation('feature', $feature);
|
||||
```
|
||||
|
||||
## Prefer `whereIn` + Subquery Over `whereHas`
|
||||
|
||||
`whereHas()` emits a correlated `EXISTS` subquery that re-executes per row. Using `whereIn()` with a `select('id')` subquery lets the database use an index lookup instead, without loading data into PHP memory.
|
||||
|
||||
Incorrect (correlated EXISTS re-executes per row):
|
||||
|
||||
```php
|
||||
$query->whereHas('company', fn ($q) => $q->where('name', 'like', $term));
|
||||
```
|
||||
|
||||
Correct (index-friendly subquery, no PHP memory overhead):
|
||||
|
||||
```php
|
||||
$query->whereIn('company_id', Company::where('name', 'like', $term)->select('id'));
|
||||
```
|
||||
|
||||
## Sometimes Two Simple Queries Beat One Complex Query
|
||||
|
||||
Running a small, targeted secondary query and passing its results via `whereIn` is often faster than a single complex correlated subquery or join. The additional round-trip is worthwhile when the secondary query is highly selective and uses its own index.
|
||||
|
||||
## Use Compound Indexes Matching `orderBy` Column Order
|
||||
|
||||
When ordering by multiple columns, create a single compound index in the same column order as the `ORDER BY` clause. Individual single-column indexes cannot combine for multi-column sorts — the database will filesort without a compound index.
|
||||
|
||||
```php
|
||||
// Migration
|
||||
$table->index(['last_name', 'first_name']);
|
||||
|
||||
// Query — column order must match the index
|
||||
User::query()->orderBy('last_name')->orderBy('first_name')->paginate();
|
||||
```
|
||||
|
||||
## Use Correlated Subqueries for Has-Many Ordering
|
||||
|
||||
When sorting by a value from a has-many relationship, avoid joins (they duplicate rows). Use a correlated subquery inside `orderBy()` instead, paired with an `addSelect` scope for eager loading.
|
||||
|
||||
```php
|
||||
public function scopeOrderByLastLogin($query): void
|
||||
{
|
||||
$query->orderByDesc(Login::select('created_at')
|
||||
->whereColumn('user_id', 'users.id')
|
||||
->latest()
|
||||
->take(1)
|
||||
);
|
||||
}
|
||||
```
|
||||
|
|
@ -1,202 +0,0 @@
|
|||
# Architecture Best Practices
|
||||
|
||||
## Single-Purpose Action Classes
|
||||
|
||||
Extract discrete business operations into invokable Action classes.
|
||||
|
||||
```php
|
||||
class CreateOrderAction
|
||||
{
|
||||
public function __construct(private InventoryService $inventory) {}
|
||||
|
||||
public function handle(array $data): Order
|
||||
{
|
||||
$order = Order::create($data);
|
||||
$this->inventory->reserve($order);
|
||||
|
||||
return $order;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Use Dependency Injection
|
||||
|
||||
Always use constructor injection. Avoid `app()` or `resolve()` inside classes.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
class OrderController extends Controller
|
||||
{
|
||||
public function store(StoreOrderRequest $request)
|
||||
{
|
||||
$service = app(OrderService::class);
|
||||
|
||||
return $service->create($request->validated());
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
class OrderController extends Controller
|
||||
{
|
||||
public function __construct(private OrderService $service) {}
|
||||
|
||||
public function store(StoreOrderRequest $request)
|
||||
{
|
||||
return $this->service->create($request->validated());
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Code to Interfaces
|
||||
|
||||
Depend on contracts at system boundaries (payment gateways, notification channels, external APIs) for testability and swappability.
|
||||
|
||||
Incorrect (concrete dependency):
|
||||
```php
|
||||
class OrderService
|
||||
{
|
||||
public function __construct(private StripeGateway $gateway) {}
|
||||
}
|
||||
```
|
||||
|
||||
Correct (interface dependency):
|
||||
```php
|
||||
interface PaymentGateway
|
||||
{
|
||||
public function charge(int $amount, string $customerId): PaymentResult;
|
||||
}
|
||||
|
||||
class OrderService
|
||||
{
|
||||
public function __construct(private PaymentGateway $gateway) {}
|
||||
}
|
||||
```
|
||||
|
||||
Bind in a service provider:
|
||||
|
||||
```php
|
||||
$this->app->bind(PaymentGateway::class, StripeGateway::class);
|
||||
```
|
||||
|
||||
## Default Sort by Descending
|
||||
|
||||
When no explicit order is specified, sort by `id` or `created_at` descending. Without an explicit `ORDER BY`, row order is undefined.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
$posts = Post::paginate();
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
$posts = Post::latest()->paginate();
|
||||
```
|
||||
|
||||
## Use Atomic Locks for Race Conditions
|
||||
|
||||
Prevent race conditions with `Cache::lock()` or `lockForUpdate()`.
|
||||
|
||||
```php
|
||||
Cache::lock('order-processing-'.$order->id, 10)->block(5, function () use ($order) {
|
||||
$order->process();
|
||||
});
|
||||
|
||||
// Or at query level
|
||||
$product = Product::where('id', $id)->lockForUpdate()->first();
|
||||
```
|
||||
|
||||
## Use `mb_*` String Functions
|
||||
|
||||
When no Laravel helper exists, prefer `mb_strlen`, `mb_strtolower`, etc. for UTF-8 safety. Standard PHP string functions count bytes, not characters.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
strlen('José'); // 5 (bytes, not characters)
|
||||
strtolower('MÜNCHEN'); // 'mÜnchen' — fails on multibyte
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
mb_strlen('José'); // 4 (characters)
|
||||
mb_strtolower('MÜNCHEN'); // 'münchen'
|
||||
|
||||
// Prefer Laravel's Str helpers when available
|
||||
Str::length('José'); // 4
|
||||
Str::lower('MÜNCHEN'); // 'münchen'
|
||||
```
|
||||
|
||||
## Use `defer()` for Post-Response Work
|
||||
|
||||
For lightweight tasks that don't need to survive a crash (logging, analytics, cleanup), use `defer()` instead of dispatching a job. The callback runs after the HTTP response is sent — no queue overhead.
|
||||
|
||||
Incorrect (job overhead for trivial work):
|
||||
```php
|
||||
dispatch(new LogPageView($page));
|
||||
```
|
||||
|
||||
Correct (runs after response, same process):
|
||||
```php
|
||||
defer(fn () => PageView::create(['page_id' => $page->id, 'user_id' => auth()->id()]));
|
||||
```
|
||||
|
||||
Use jobs when the work must survive process crashes or needs retry logic. Use `defer()` for fire-and-forget work.
|
||||
|
||||
## Use `Context` for Request-Scoped Data
|
||||
|
||||
The `Context` facade passes data through the entire request lifecycle — middleware, controllers, jobs, logs — without passing arguments manually.
|
||||
|
||||
```php
|
||||
// In middleware
|
||||
Context::add('tenant_id', $request->header('X-Tenant-ID'));
|
||||
|
||||
// Anywhere later — controllers, jobs, log context
|
||||
$tenantId = Context::get('tenant_id');
|
||||
```
|
||||
|
||||
Context data automatically propagates to queued jobs and is included in log entries. Use `Context::addHidden()` for sensitive data that should be available in queued jobs but excluded from log context. If data must not leave the current process, do not store it in `Context`.
|
||||
|
||||
## Use `Concurrency::run()` for Parallel Execution
|
||||
|
||||
Run independent operations in parallel using child processes — no async libraries needed.
|
||||
|
||||
```php
|
||||
use Illuminate\Support\Facades\Concurrency;
|
||||
|
||||
[$users, $orders] = Concurrency::run([
|
||||
fn () => User::count(),
|
||||
fn () => Order::where('status', 'pending')->count(),
|
||||
]);
|
||||
```
|
||||
|
||||
Each closure runs in a separate process with full Laravel access. Use for independent database queries, API calls, or computations that would otherwise run sequentially.
|
||||
|
||||
## Convention Over Configuration
|
||||
|
||||
Follow Laravel conventions. Don't override defaults unnecessarily.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
class Customer extends Model
|
||||
{
|
||||
protected $table = 'Customer';
|
||||
protected $primaryKey = 'customer_id';
|
||||
|
||||
public function roles(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Role::class, 'role_customer', 'customer_id', 'role_id');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
class Customer extends Model
|
||||
{
|
||||
public function roles(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Role::class);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
|
@ -1,36 +0,0 @@
|
|||
# Blade & Views Best Practices
|
||||
|
||||
## Use `$attributes->merge()` in Component Templates
|
||||
|
||||
Hardcoding classes prevents consumers from adding their own. `merge()` combines class attributes cleanly.
|
||||
|
||||
```blade
|
||||
<div {{ $attributes->merge(['class' => 'alert alert-'.$type]) }}>
|
||||
{{ $message }}
|
||||
</div>
|
||||
```
|
||||
|
||||
## Use `@pushOnce` for Per-Component Scripts
|
||||
|
||||
If a component renders inside a `@foreach`, `@push` inserts the script N times. `@pushOnce` guarantees it's included exactly once.
|
||||
|
||||
## Prefer Blade Components Over `@include`
|
||||
|
||||
`@include` shares all parent variables implicitly (hidden coupling). Components have explicit props, attribute bags, and slots.
|
||||
|
||||
## Use View Composers for Shared View Data
|
||||
|
||||
If every controller rendering a sidebar must pass `$categories`, that's duplicated code. A View Composer centralizes it.
|
||||
|
||||
## Use Blade Fragments for Partial Re-Renders (htmx/Turbo)
|
||||
|
||||
A single view can return either the full page or just a fragment, keeping routing clean.
|
||||
|
||||
```php
|
||||
return view('dashboard', compact('users'))
|
||||
->fragmentIf($request->hasHeader('HX-Request'), 'user-list');
|
||||
```
|
||||
|
||||
## Use `@aware` for Deeply Nested Component Props
|
||||
|
||||
Avoids re-passing parent props through every level of nested components.
|
||||
|
|
@ -1,70 +0,0 @@
|
|||
# Caching Best Practices
|
||||
|
||||
## Use `Cache::remember()` Instead of Manual Get/Put
|
||||
|
||||
Cleaner cache-aside pattern that removes boilerplate. use `Cache::lock()` for race conditions.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
$val = Cache::get('stats');
|
||||
if (! $val) {
|
||||
$val = $this->computeStats();
|
||||
Cache::put('stats', $val, 60);
|
||||
}
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
$val = Cache::remember('stats', 60, fn () => $this->computeStats());
|
||||
```
|
||||
|
||||
## Use `Cache::flexible()` for Stale-While-Revalidate
|
||||
|
||||
On high-traffic keys, one user always gets a slow response when the cache expires. `flexible()` serves slightly stale data while refreshing in the background.
|
||||
|
||||
Incorrect: `Cache::remember('users', 300, fn () => User::all());`
|
||||
|
||||
Correct: `Cache::flexible('users', [300, 600], fn () => User::all());` — fresh for 5 min, stale-but-served up to 10 min, refreshes via deferred function.
|
||||
|
||||
## Use `Cache::memo()` to Avoid Redundant Hits Within a Request
|
||||
|
||||
If the same cache key is read multiple times per request (e.g., a service called from multiple places), `memo()` stores the resolved value in memory.
|
||||
|
||||
`Cache::memo()->get('settings');` — 5 calls = 1 Redis round-trip instead of 5.
|
||||
|
||||
## Use Cache Tags to Invalidate Related Groups
|
||||
|
||||
Without tags, invalidating a group of entries requires tracking every key. Tags let you flush atomically. Only works with `redis`, `memcached`, `dynamodb` — not `file` or `database`.
|
||||
|
||||
```php
|
||||
Cache::tags(['user-1'])->flush();
|
||||
```
|
||||
|
||||
## Use `Cache::add()` for Atomic Conditional Writes
|
||||
|
||||
`add()` only writes if the key does not exist — atomic, no race condition between checking and writing.
|
||||
|
||||
Incorrect: `if (! Cache::has('lock')) { Cache::put('lock', true, 10); }`
|
||||
|
||||
Correct: `Cache::add('lock', true, 10);`
|
||||
|
||||
## Use `once()` for Per-Request Memoization
|
||||
|
||||
`once()` memoizes a function's return value for the lifetime of the object (or request for closures). Unlike `Cache::memo()`, it doesn't hit the cache store at all — pure in-memory.
|
||||
|
||||
```php
|
||||
public function roles(): Collection
|
||||
{
|
||||
return once(fn () => $this->loadRoles());
|
||||
}
|
||||
```
|
||||
|
||||
Multiple calls return the cached result without re-executing. Use `once()` for expensive computations called multiple times per request. Use `Cache::memo()` when you also want cross-request caching.
|
||||
|
||||
## Configure Failover Cache Stores in Production
|
||||
|
||||
If Redis goes down, the app falls back to a secondary store automatically.
|
||||
|
||||
```php
|
||||
'failover' => ['driver' => 'failover', 'stores' => ['redis', 'database']],
|
||||
```
|
||||
|
|
@ -1,44 +0,0 @@
|
|||
# Collection Best Practices
|
||||
|
||||
## Use Higher-Order Messages for Simple Operations
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
$users->each(function (User $user) {
|
||||
$user->markAsVip();
|
||||
});
|
||||
```
|
||||
|
||||
Correct: `$users->each->markAsVip();`
|
||||
|
||||
Works with `each`, `map`, `sum`, `filter`, `reject`, `contains`, etc.
|
||||
|
||||
## Choose `cursor()` vs. `lazy()` Correctly
|
||||
|
||||
- `cursor()` — one model in memory, but cannot eager-load relationships (N+1 risk).
|
||||
- `lazy()` — chunked pagination returning a flat LazyCollection, supports eager loading.
|
||||
|
||||
Incorrect: `User::with('roles')->cursor()` — eager loading silently ignored.
|
||||
|
||||
Correct: `User::with('roles')->lazy()` for relationship access; `User::cursor()` for attribute-only work.
|
||||
|
||||
## Use `lazyById()` When Updating Records While Iterating
|
||||
|
||||
`lazy()` uses offset pagination — updating records during iteration can skip or double-process. `lazyById()` uses `id > last_id`, safe against mutation.
|
||||
|
||||
## Use `toQuery()` for Bulk Operations on Collections
|
||||
|
||||
Avoids manual `whereIn` construction.
|
||||
|
||||
Incorrect: `User::whereIn('id', $users->pluck('id'))->update([...]);`
|
||||
|
||||
Correct: `$users->toQuery()->update([...]);`
|
||||
|
||||
## Use `#[CollectedBy]` for Custom Collection Classes
|
||||
|
||||
More declarative than overriding `newCollection()`.
|
||||
|
||||
```php
|
||||
#[CollectedBy(UserCollection::class)]
|
||||
class User extends Model {}
|
||||
```
|
||||
|
|
@ -1,73 +0,0 @@
|
|||
# Configuration Best Practices
|
||||
|
||||
## `env()` Only in Config Files
|
||||
|
||||
Direct `env()` calls may return `null` when config is cached.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
$key = env('API_KEY');
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
// config/services.php
|
||||
'key' => env('API_KEY'),
|
||||
|
||||
// Application code
|
||||
$key = config('services.key');
|
||||
```
|
||||
|
||||
## Use Encrypted Env or External Secrets
|
||||
|
||||
Never store production secrets in plain `.env` files in version control.
|
||||
|
||||
Incorrect:
|
||||
```bash
|
||||
|
||||
# .env committed to repo or shared in Slack
|
||||
|
||||
STRIPE_SECRET=sk_live_abc123
|
||||
AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI
|
||||
```
|
||||
|
||||
Correct:
|
||||
```bash
|
||||
php artisan env:encrypt --env=production --readable
|
||||
php artisan env:decrypt --env=production
|
||||
```
|
||||
|
||||
For cloud deployments, prefer the platform's native secret store (AWS Secrets Manager, Vault, etc.) and inject at runtime.
|
||||
|
||||
## Use `App::environment()` for Environment Checks
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
if (env('APP_ENV') === 'production') {
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
if (app()->isProduction()) {
|
||||
// or
|
||||
if (App::environment('production')) {
|
||||
```
|
||||
|
||||
## Use Constants and Language Files
|
||||
|
||||
Use class constants instead of hardcoded magic strings for model states, types, and statuses.
|
||||
|
||||
```php
|
||||
// Incorrect
|
||||
return $this->type === 'normal';
|
||||
|
||||
// Correct
|
||||
return $this->type === self::TYPE_NORMAL;
|
||||
```
|
||||
|
||||
If the application already uses language files for localization, use `__()` for user-facing strings too. Do not introduce language files purely for English-only apps — simple string literals are fine there.
|
||||
|
||||
```php
|
||||
// Only when lang files already exist in the project
|
||||
return back()->with('message', __('app.article_added'));
|
||||
```
|
||||
|
|
@ -1,192 +0,0 @@
|
|||
# Database Performance Best Practices
|
||||
|
||||
## Always Eager Load Relationships
|
||||
|
||||
Lazy loading causes N+1 query problems — one query per loop iteration. Always use `with()` to load relationships upfront.
|
||||
|
||||
Incorrect (N+1 — executes 1 + N queries):
|
||||
```php
|
||||
$posts = Post::all();
|
||||
foreach ($posts as $post) {
|
||||
echo $post->author->name;
|
||||
}
|
||||
```
|
||||
|
||||
Correct (2 queries total):
|
||||
```php
|
||||
$posts = Post::with('author')->get();
|
||||
foreach ($posts as $post) {
|
||||
echo $post->author->name;
|
||||
}
|
||||
```
|
||||
|
||||
Constrain eager loads to select only needed columns (always include the foreign key):
|
||||
|
||||
```php
|
||||
$users = User::with(['posts' => function ($query) {
|
||||
$query->select('id', 'user_id', 'title')
|
||||
->where('published', true)
|
||||
->latest()
|
||||
->limit(10);
|
||||
}])->get();
|
||||
```
|
||||
|
||||
## Prevent Lazy Loading in Development
|
||||
|
||||
Enable this in `AppServiceProvider::boot()` to catch N+1 issues during development.
|
||||
|
||||
```php
|
||||
public function boot(): void
|
||||
{
|
||||
Model::preventLazyLoading(! app()->isProduction());
|
||||
}
|
||||
```
|
||||
|
||||
Throws `LazyLoadingViolationException` when a relationship is accessed without being eager-loaded.
|
||||
|
||||
## Select Only Needed Columns
|
||||
|
||||
Avoid `SELECT *` — especially when tables have large text or JSON columns.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
$posts = Post::with('author')->get();
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
$posts = Post::select('id', 'title', 'user_id', 'created_at')
|
||||
->with(['author:id,name,avatar'])
|
||||
->get();
|
||||
```
|
||||
|
||||
When selecting columns on eager-loaded relationships, always include the foreign key column or the relationship won't match.
|
||||
|
||||
## Chunk Large Datasets
|
||||
|
||||
Never load thousands of records at once. Use chunking for batch processing.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
$users = User::all();
|
||||
foreach ($users as $user) {
|
||||
$user->notify(new WeeklyDigest);
|
||||
}
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
User::where('subscribed', true)->chunk(200, function ($users) {
|
||||
foreach ($users as $user) {
|
||||
$user->notify(new WeeklyDigest);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
Use `chunkById()` when modifying records during iteration — standard `chunk()` uses OFFSET which shifts when rows change:
|
||||
|
||||
```php
|
||||
User::where('active', false)->chunkById(200, function ($users) {
|
||||
$users->each->delete();
|
||||
});
|
||||
```
|
||||
|
||||
## Add Database Indexes
|
||||
|
||||
Index columns that appear in `WHERE`, `ORDER BY`, `JOIN`, and `GROUP BY` clauses.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
Schema::create('orders', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('user_id')->constrained();
|
||||
$table->string('status');
|
||||
$table->timestamps();
|
||||
});
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
Schema::create('orders', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('user_id')->index()->constrained();
|
||||
$table->string('status')->index();
|
||||
$table->timestamps();
|
||||
$table->index(['status', 'created_at']);
|
||||
});
|
||||
```
|
||||
|
||||
Add composite indexes for common query patterns (e.g., `WHERE status = ? ORDER BY created_at`).
|
||||
|
||||
## Use `withCount()` for Counting Relations
|
||||
|
||||
Never load entire collections just to count them.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
$posts = Post::all();
|
||||
foreach ($posts as $post) {
|
||||
echo $post->comments->count();
|
||||
}
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
$posts = Post::withCount('comments')->get();
|
||||
foreach ($posts as $post) {
|
||||
echo $post->comments_count;
|
||||
}
|
||||
```
|
||||
|
||||
Conditional counting:
|
||||
|
||||
```php
|
||||
$posts = Post::withCount([
|
||||
'comments',
|
||||
'comments as approved_comments_count' => function ($query) {
|
||||
$query->where('approved', true);
|
||||
},
|
||||
])->get();
|
||||
```
|
||||
|
||||
## Use `cursor()` for Memory-Efficient Iteration
|
||||
|
||||
For read-only iteration over large result sets, `cursor()` loads one record at a time via a PHP generator.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
$users = User::where('active', true)->get();
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
foreach (User::where('active', true)->cursor() as $user) {
|
||||
ProcessUser::dispatch($user->id);
|
||||
}
|
||||
```
|
||||
|
||||
Use `cursor()` for read-only iteration. Use `chunk()` / `chunkById()` when modifying records.
|
||||
|
||||
## No Queries in Blade Templates
|
||||
|
||||
Never execute queries in Blade templates. Pass data from controllers.
|
||||
|
||||
Incorrect:
|
||||
```blade
|
||||
@foreach (User::all() as $user)
|
||||
{{ $user->profile->name }}
|
||||
@endforeach
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
// Controller
|
||||
$users = User::with('profile')->get();
|
||||
return view('users.index', compact('users'));
|
||||
```
|
||||
|
||||
```blade
|
||||
@foreach ($users as $user)
|
||||
{{ $user->profile->name }}
|
||||
@endforeach
|
||||
```
|
||||
|
|
@ -1,150 +0,0 @@
|
|||
# Eloquent Best Practices
|
||||
|
||||
## Use Correct Relationship Types
|
||||
|
||||
Use `hasMany`, `belongsTo`, `morphMany`, etc. with proper return type hints.
|
||||
|
||||
```php
|
||||
public function comments(): HasMany
|
||||
{
|
||||
return $this->hasMany(Comment::class);
|
||||
}
|
||||
|
||||
public function author(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'user_id');
|
||||
}
|
||||
```
|
||||
|
||||
## Use Local Scopes for Reusable Queries
|
||||
|
||||
Extract reusable query constraints into local scopes to avoid duplication.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
$active = User::where('verified', true)->whereNotNull('activated_at')->get();
|
||||
$articles = Article::whereHas('user', function ($q) {
|
||||
$q->where('verified', true)->whereNotNull('activated_at');
|
||||
})->get();
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
#[Scope]
|
||||
protected function active(Builder $query): Builder
|
||||
{
|
||||
return $query->where('verified', true)->whereNotNull('activated_at');
|
||||
}
|
||||
|
||||
// Usage
|
||||
$active = User::active()->get();
|
||||
$articles = Article::whereHas('user', fn ($q) => $q->active())->get();
|
||||
```
|
||||
|
||||
## Apply Global Scopes Sparingly
|
||||
|
||||
Global scopes silently modify every query on the model, making debugging difficult. Prefer local scopes and reserve global scopes for truly universal constraints like soft deletes or multi-tenancy.
|
||||
|
||||
Incorrect (global scope for a conditional filter):
|
||||
```php
|
||||
class PublishedScope implements Scope
|
||||
{
|
||||
public function apply(Builder $builder, Model $model): void
|
||||
{
|
||||
$builder->where('published', true);
|
||||
}
|
||||
}
|
||||
// Now admin panels, reports, and background jobs all silently skip drafts
|
||||
```
|
||||
|
||||
Correct (local scope you opt into):
|
||||
```php
|
||||
#[Scope]
|
||||
protected function published(Builder $query): Builder
|
||||
{
|
||||
return $query->where('published', true);
|
||||
}
|
||||
|
||||
Post::published()->paginate(); // Explicit
|
||||
Post::paginate(); // Admin sees all
|
||||
```
|
||||
|
||||
## Define Attribute Casts
|
||||
|
||||
Use the `casts()` method (or `$casts` property following project convention) for automatic type conversion.
|
||||
|
||||
```php
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'is_active' => 'boolean',
|
||||
'metadata' => 'array',
|
||||
'total' => 'decimal:2',
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
## Cast Date Columns Properly
|
||||
|
||||
Always cast date columns. Use Carbon instances in templates instead of formatting strings manually.
|
||||
|
||||
Incorrect:
|
||||
```blade
|
||||
{{ Carbon::createFromFormat('Y-d-m H-i', $order->ordered_at)->toDateString() }}
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'ordered_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
```blade
|
||||
{{ $order->ordered_at->toDateString() }}
|
||||
{{ $order->ordered_at->format('m-d') }}
|
||||
```
|
||||
|
||||
## Use `whereBelongsTo()` for Relationship Queries
|
||||
|
||||
Cleaner than manually specifying foreign keys.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
Post::where('user_id', $user->id)->get();
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
Post::whereBelongsTo($user)->get();
|
||||
Post::whereBelongsTo($user, 'author')->get();
|
||||
```
|
||||
|
||||
## Avoid Hardcoded Table Names in Queries
|
||||
|
||||
Never use string literals for table names in raw queries, joins, or subqueries. Hardcoded table names make it impossible to find all places a model is used and break refactoring (e.g., renaming a table requires hunting through every raw string).
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
DB::table('users')->where('active', true)->get();
|
||||
|
||||
$query->join('companies', 'companies.id', '=', 'users.company_id');
|
||||
|
||||
DB::select('SELECT * FROM orders WHERE status = ?', ['pending']);
|
||||
```
|
||||
|
||||
Correct — reference the model's table:
|
||||
```php
|
||||
DB::table((new User)->getTable())->where('active', true)->get();
|
||||
|
||||
// Even better — use Eloquent or the query builder instead of raw SQL
|
||||
User::where('active', true)->get();
|
||||
Order::where('status', 'pending')->get();
|
||||
```
|
||||
|
||||
Prefer Eloquent queries and relationships over `DB::table()` whenever possible — they already reference the model's table. When `DB::table()` or raw joins are unavoidable, always use `(new Model)->getTable()` to keep the reference traceable.
|
||||
|
||||
**Exception — migrations:** In migrations, hardcoded table names via `DB::table('settings')` are acceptable and preferred. Models change over time but migrations are frozen snapshots — referencing a model that is later renamed or deleted would break the migration.
|
||||
|
|
@ -1,72 +0,0 @@
|
|||
# Error Handling Best Practices
|
||||
|
||||
## Exception Reporting and Rendering
|
||||
|
||||
There are two valid approaches — choose one and apply it consistently across the project.
|
||||
|
||||
**Co-location on the exception class** — keeps behavior alongside the exception definition, easier to find:
|
||||
|
||||
```php
|
||||
class InvalidOrderException extends Exception
|
||||
{
|
||||
public function report(): void { /* custom reporting */ }
|
||||
|
||||
public function render(Request $request): Response
|
||||
{
|
||||
return response()->view('errors.invalid-order', status: 422);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Centralized in `bootstrap/app.php`** — all exception handling in one place, easier to see the full picture:
|
||||
|
||||
```php
|
||||
->withExceptions(function (Exceptions $exceptions) {
|
||||
$exceptions->report(function (InvalidOrderException $e) { /* ... */ });
|
||||
$exceptions->render(function (InvalidOrderException $e, Request $request) {
|
||||
return response()->view('errors.invalid-order', status: 422);
|
||||
});
|
||||
})
|
||||
```
|
||||
|
||||
Check the existing codebase and follow whichever pattern is already established.
|
||||
|
||||
## Use `ShouldntReport` for Exceptions That Should Never Log
|
||||
|
||||
More discoverable than listing classes in `dontReport()`.
|
||||
|
||||
```php
|
||||
class PodcastProcessingException extends Exception implements ShouldntReport {}
|
||||
```
|
||||
|
||||
## Throttle High-Volume Exceptions
|
||||
|
||||
A single failing integration can flood error tracking. Use `throttle()` to rate-limit per exception type.
|
||||
|
||||
## Enable `dontReportDuplicates()`
|
||||
|
||||
Prevents the same exception instance from being logged multiple times when `report($e)` is called in multiple catch blocks.
|
||||
|
||||
## Force JSON Error Rendering for API Routes
|
||||
|
||||
Laravel auto-detects `Accept: application/json` but API clients may not set it. Explicitly declare JSON rendering for API routes.
|
||||
|
||||
```php
|
||||
$exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) {
|
||||
return $request->is('api/*') || $request->expectsJson();
|
||||
});
|
||||
```
|
||||
|
||||
## Add Context to Exception Classes
|
||||
|
||||
Attach structured data to exceptions at the source via a `context()` method — Laravel includes it automatically in the log entry.
|
||||
|
||||
```php
|
||||
class InvalidOrderException extends Exception
|
||||
{
|
||||
public function context(): array
|
||||
{
|
||||
return ['order_id' => $this->orderId];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
|
@ -1,52 +0,0 @@
|
|||
# Events & Notifications Best Practices
|
||||
|
||||
## Rely on Event Discovery
|
||||
|
||||
Laravel auto-discovers listeners by reading `handle(EventType $event)` type-hints. No manual registration needed in `AppServiceProvider`.
|
||||
|
||||
## Run `event:cache` in Production Deploy
|
||||
|
||||
Event discovery scans the filesystem per-request in dev. Cache it in production: `php artisan optimize` or `php artisan event:cache`.
|
||||
|
||||
## Use `ShouldDispatchAfterCommit` Inside Transactions
|
||||
|
||||
Without it, a queued listener may process before the DB transaction commits, reading data that doesn't exist yet.
|
||||
|
||||
```php
|
||||
class OrderShipped implements ShouldDispatchAfterCommit {}
|
||||
```
|
||||
|
||||
## Always Queue Notifications
|
||||
|
||||
Notifications often hit external APIs (email, SMS, Slack). Without `ShouldQueue`, they block the HTTP response.
|
||||
|
||||
```php
|
||||
class InvoicePaid extends Notification implements ShouldQueue
|
||||
{
|
||||
use Queueable;
|
||||
}
|
||||
```
|
||||
|
||||
## Use `afterCommit()` on Notifications in Transactions
|
||||
|
||||
Same race condition as events — call `afterCommit()` to delay dispatch until the transaction commits.
|
||||
|
||||
```php
|
||||
$user->notify((new InvoicePaid($invoice))->afterCommit());
|
||||
```
|
||||
|
||||
## Route Notification Channels to Dedicated Queues
|
||||
|
||||
Mail and database notifications have different priorities. Use `viaQueues()` to route them to separate queues.
|
||||
|
||||
## Use On-Demand Notifications for Non-User Recipients
|
||||
|
||||
Avoid creating dummy models to send notifications to arbitrary addresses.
|
||||
|
||||
```php
|
||||
Notification::route('mail', 'admin@example.com')->notify(new SystemAlert());
|
||||
```
|
||||
|
||||
## Implement `HasLocalePreference` on Notifiable Models
|
||||
|
||||
Laravel automatically uses the user's preferred locale for all notifications and mailables — no per-call `locale()` needed.
|
||||
|
|
@ -1,160 +0,0 @@
|
|||
# HTTP Client Best Practices
|
||||
|
||||
## Always Set Explicit Timeouts
|
||||
|
||||
The default timeout is 30 seconds — too long for most API calls. Always set explicit `timeout` and `connectTimeout` to fail fast.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
$response = Http::get('https://api.example.com/users');
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
$response = Http::timeout(5)
|
||||
->connectTimeout(3)
|
||||
->get('https://api.example.com/users');
|
||||
```
|
||||
|
||||
For service-specific clients, define timeouts in a macro:
|
||||
|
||||
```php
|
||||
Http::macro('github', function () {
|
||||
return Http::baseUrl('https://api.github.com')
|
||||
->timeout(10)
|
||||
->connectTimeout(3)
|
||||
->withToken(config('services.github.token'));
|
||||
});
|
||||
|
||||
$response = Http::github()->get('/repos/laravel/framework');
|
||||
```
|
||||
|
||||
## Use Retry with Backoff for External APIs
|
||||
|
||||
External APIs have transient failures. Use `retry()` with increasing delays.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
$response = Http::post('https://api.stripe.com/v1/charges', $data);
|
||||
|
||||
if ($response->failed()) {
|
||||
throw new PaymentFailedException('Charge failed');
|
||||
}
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
$response = Http::retry([100, 500, 1000])
|
||||
->timeout(10)
|
||||
->post('https://api.stripe.com/v1/charges', $data);
|
||||
```
|
||||
|
||||
Only retry on specific errors:
|
||||
|
||||
```php
|
||||
$response = Http::retry(3, 100, function (Throwable $exception, PendingRequest $request) {
|
||||
return $exception instanceof ConnectionException
|
||||
|| ($exception instanceof RequestException && $exception->response->serverError());
|
||||
})->post('https://api.example.com/data');
|
||||
```
|
||||
|
||||
## Handle Errors Explicitly
|
||||
|
||||
The HTTP Client does not throw on 4xx/5xx by default. Always check status or use `throw()`.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
$response = Http::get('https://api.example.com/users/1');
|
||||
$user = $response->json(); // Could be an error body
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
$response = Http::timeout(5)
|
||||
->get('https://api.example.com/users/1')
|
||||
->throw();
|
||||
|
||||
$user = $response->json();
|
||||
```
|
||||
|
||||
For graceful degradation:
|
||||
|
||||
```php
|
||||
$response = Http::get('https://api.example.com/users/1');
|
||||
|
||||
if ($response->successful()) {
|
||||
return $response->json();
|
||||
}
|
||||
|
||||
if ($response->notFound()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$response->throw();
|
||||
```
|
||||
|
||||
## Use Request Pooling for Concurrent Requests
|
||||
|
||||
When making multiple independent API calls, use `Http::pool()` instead of sequential calls.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
$users = Http::get('https://api.example.com/users')->json();
|
||||
$posts = Http::get('https://api.example.com/posts')->json();
|
||||
$comments = Http::get('https://api.example.com/comments')->json();
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
use Illuminate\Http\Client\Pool;
|
||||
|
||||
$responses = Http::pool(fn (Pool $pool) => [
|
||||
$pool->as('users')->get('https://api.example.com/users'),
|
||||
$pool->as('posts')->get('https://api.example.com/posts'),
|
||||
$pool->as('comments')->get('https://api.example.com/comments'),
|
||||
]);
|
||||
|
||||
$users = $responses['users']->json();
|
||||
$posts = $responses['posts']->json();
|
||||
```
|
||||
|
||||
## Fake HTTP Calls in Tests
|
||||
|
||||
Never make real HTTP requests in tests. Use `Http::fake()` and `preventStrayRequests()`.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
it('syncs user from API', function () {
|
||||
$service = new UserSyncService;
|
||||
$service->sync(1); // Hits the real API
|
||||
});
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
it('syncs user from API', function () {
|
||||
Http::preventStrayRequests();
|
||||
|
||||
Http::fake([
|
||||
'api.example.com/users/1' => Http::response([
|
||||
'name' => 'John Doe',
|
||||
'email' => 'john@example.com',
|
||||
]),
|
||||
]);
|
||||
|
||||
$service = new UserSyncService;
|
||||
$service->sync(1);
|
||||
|
||||
Http::assertSent(function (Request $request) {
|
||||
return $request->url() === 'https://api.example.com/users/1';
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
Test failure scenarios too:
|
||||
|
||||
```php
|
||||
Http::fake([
|
||||
'api.example.com/*' => Http::failedConnection(),
|
||||
]);
|
||||
```
|
||||
|
|
@ -1,27 +0,0 @@
|
|||
# Mail Best Practices
|
||||
|
||||
## Implement `ShouldQueue` on the Mailable Class
|
||||
|
||||
Makes queueing the default regardless of how the mailable is dispatched. No need to remember `Mail::queue()` at every call site — `Mail::send()` also queues it.
|
||||
|
||||
## Use `afterCommit()` on Mailables Inside Transactions
|
||||
|
||||
A queued mailable dispatched inside a transaction may process before the commit. Use `$this->afterCommit()` in the constructor.
|
||||
|
||||
## Use `assertQueued()` Not `assertSent()` for Queued Mailables
|
||||
|
||||
`Mail::assertSent()` only catches synchronous mail. Queued mailables fail `assertSent` with a "Did you mean to use assertQueued()?" hint.
|
||||
|
||||
Incorrect: `Mail::assertSent(OrderShipped::class);` when mailable implements `ShouldQueue`.
|
||||
|
||||
Correct: `Mail::assertQueued(OrderShipped::class);`
|
||||
|
||||
## Use Markdown Mailables for Transactional Emails
|
||||
|
||||
Markdown mailables auto-generate both HTML and plain-text versions, use responsive components, and allow global style customization. Generate with `--markdown` flag.
|
||||
|
||||
## Separate Content Tests from Sending Tests
|
||||
|
||||
Content tests: instantiate the mailable directly, call `assertSeeInHtml()`.
|
||||
Sending tests: use `Mail::fake()` and `assertSent()`/`assertQueued()`.
|
||||
Don't mix them — it conflates concerns and makes tests brittle.
|
||||
|
|
@ -1,121 +0,0 @@
|
|||
# Migration Best Practices
|
||||
|
||||
## Generate Migrations with Artisan
|
||||
|
||||
Always use `php artisan make:migration` for consistent naming and timestamps.
|
||||
|
||||
Incorrect (manually created file):
|
||||
```php
|
||||
// database/migrations/posts_migration.php ← wrong naming, no timestamp
|
||||
```
|
||||
|
||||
Correct (Artisan-generated):
|
||||
```bash
|
||||
php artisan make:migration create_posts_table
|
||||
php artisan make:migration add_slug_to_posts_table
|
||||
```
|
||||
|
||||
## Use `constrained()` for Foreign Keys
|
||||
|
||||
Automatic naming and referential integrity.
|
||||
|
||||
```php
|
||||
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
|
||||
|
||||
// Non-standard names
|
||||
$table->foreignId('author_id')->constrained('users');
|
||||
```
|
||||
|
||||
## Never Modify Deployed Migrations
|
||||
|
||||
Once a migration has run in production, treat it as immutable. Create a new migration to change the table.
|
||||
|
||||
Incorrect (editing a deployed migration):
|
||||
```php
|
||||
// 2024_01_01_create_posts_table.php — already in production
|
||||
$table->string('slug')->unique(); // ← added after deployment
|
||||
```
|
||||
|
||||
Correct (new migration to alter):
|
||||
```php
|
||||
// 2024_03_15_add_slug_to_posts_table.php
|
||||
Schema::table('posts', function (Blueprint $table) {
|
||||
$table->string('slug')->unique()->after('title');
|
||||
});
|
||||
```
|
||||
|
||||
## Add Indexes in the Migration
|
||||
|
||||
Add indexes when creating the table, not as an afterthought. Columns used in `WHERE`, `ORDER BY`, and `JOIN` clauses need indexes.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
Schema::create('orders', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('user_id')->constrained();
|
||||
$table->string('status');
|
||||
$table->timestamps();
|
||||
});
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
Schema::create('orders', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('user_id')->constrained()->index();
|
||||
$table->string('status')->index();
|
||||
$table->timestamp('shipped_at')->nullable()->index();
|
||||
$table->timestamps();
|
||||
});
|
||||
```
|
||||
|
||||
## Mirror Defaults in Model `$attributes`
|
||||
|
||||
When a column has a database default, mirror it in the model so new instances have correct values before saving.
|
||||
|
||||
```php
|
||||
// Migration
|
||||
$table->string('status')->default('pending');
|
||||
|
||||
// Model
|
||||
protected $attributes = [
|
||||
'status' => 'pending',
|
||||
];
|
||||
```
|
||||
|
||||
## Write Reversible `down()` Methods by Default
|
||||
|
||||
Implement `down()` for schema changes that can be safely reversed so `migrate:rollback` works in CI and failed deployments.
|
||||
|
||||
```php
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('posts', function (Blueprint $table) {
|
||||
$table->dropColumn('slug');
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
For intentionally irreversible migrations (e.g., destructive data backfills), leave a clear comment and require a forward fix migration instead of pretending rollback is supported.
|
||||
|
||||
## Keep Migrations Focused
|
||||
|
||||
One concern per migration. Never mix DDL (schema changes) and DML (data manipulation).
|
||||
|
||||
Incorrect (partial failure creates unrecoverable state):
|
||||
```php
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('settings', function (Blueprint $table) { ... });
|
||||
DB::table('settings')->insert(['key' => 'version', 'value' => '1.0']);
|
||||
}
|
||||
```
|
||||
|
||||
Correct (separate migrations):
|
||||
```php
|
||||
// Migration 1: create_settings_table
|
||||
Schema::create('settings', function (Blueprint $table) { ... });
|
||||
|
||||
// Migration 2: seed_default_settings
|
||||
DB::table('settings')->insert(['key' => 'version', 'value' => '1.0']);
|
||||
```
|
||||
|
|
@ -1,144 +0,0 @@
|
|||
# Queue & Job Best Practices
|
||||
|
||||
## Set `retry_after` Greater Than `timeout`
|
||||
|
||||
If `retry_after` is shorter than the job's `timeout`, the queue worker re-dispatches the job while it's still running, causing duplicate execution.
|
||||
|
||||
Incorrect (`retry_after` ≤ `timeout`):
|
||||
```php
|
||||
class ProcessReport implements ShouldQueue
|
||||
{
|
||||
public $timeout = 120;
|
||||
}
|
||||
|
||||
// config/queue.php — retry_after: 90 ← job retried while still running!
|
||||
```
|
||||
|
||||
Correct (`retry_after` > `timeout`):
|
||||
```php
|
||||
class ProcessReport implements ShouldQueue
|
||||
{
|
||||
public $timeout = 120;
|
||||
}
|
||||
|
||||
// config/queue.php — retry_after: 180 ← safely longer than any job timeout
|
||||
```
|
||||
|
||||
## Use Exponential Backoff
|
||||
|
||||
Use progressively longer delays between retries to avoid hammering failing services.
|
||||
|
||||
Incorrect (fixed retry interval):
|
||||
```php
|
||||
class SyncWithStripe implements ShouldQueue
|
||||
{
|
||||
public $tries = 3;
|
||||
// Default: retries immediately, overwhelming the API
|
||||
}
|
||||
```
|
||||
|
||||
Correct (exponential backoff):
|
||||
```php
|
||||
class SyncWithStripe implements ShouldQueue
|
||||
{
|
||||
public $tries = 3;
|
||||
public $backoff = [1, 5, 10];
|
||||
}
|
||||
```
|
||||
|
||||
## Implement `ShouldBeUnique`
|
||||
|
||||
Prevent duplicate job processing.
|
||||
|
||||
```php
|
||||
class GenerateInvoice implements ShouldQueue, ShouldBeUnique
|
||||
{
|
||||
public function uniqueId(): string
|
||||
{
|
||||
return $this->order->id;
|
||||
}
|
||||
|
||||
public $uniqueFor = 3600;
|
||||
}
|
||||
```
|
||||
|
||||
## Always Implement `failed()`
|
||||
|
||||
Handle errors explicitly — don't rely on silent failure.
|
||||
|
||||
```php
|
||||
public function failed(?Throwable $exception): void
|
||||
{
|
||||
$this->podcast->update(['status' => 'failed']);
|
||||
Log::error('Processing failed', ['id' => $this->podcast->id, 'error' => $exception->getMessage()]);
|
||||
}
|
||||
```
|
||||
|
||||
## Rate Limit External API Calls in Jobs
|
||||
|
||||
Use `RateLimited` middleware to throttle jobs calling third-party APIs.
|
||||
|
||||
```php
|
||||
public function middleware(): array
|
||||
{
|
||||
return [new RateLimited('external-api')];
|
||||
}
|
||||
```
|
||||
|
||||
## Batch Related Jobs
|
||||
|
||||
Use `Bus::batch()` when jobs should succeed or fail together.
|
||||
|
||||
```php
|
||||
Bus::batch([
|
||||
new ImportCsvChunk($chunk1),
|
||||
new ImportCsvChunk($chunk2),
|
||||
])
|
||||
->then(fn (Batch $batch) => Notification::send($user, new ImportComplete))
|
||||
->catch(fn (Batch $batch, Throwable $e) => Log::error('Batch failed'))
|
||||
->dispatch();
|
||||
```
|
||||
|
||||
## `retryUntil()` Needs `$tries = 0`
|
||||
|
||||
When using time-based retry limits, set `$tries = 0` to avoid premature failure.
|
||||
|
||||
```php
|
||||
public $tries = 0;
|
||||
|
||||
public function retryUntil(): \DateTimeInterface
|
||||
{
|
||||
return now()->addHours(4);
|
||||
}
|
||||
```
|
||||
|
||||
## Use `ShouldBeUniqueUntilProcessing` for Early Lock Release
|
||||
|
||||
`ShouldBeUnique` holds the lock until the job completes. `ShouldBeUniqueUntilProcessing` releases it when processing starts, allowing new instances to queue.
|
||||
|
||||
```php
|
||||
class UpdateSearchIndex implements ShouldQueue, ShouldBeUniqueUntilProcessing
|
||||
{
|
||||
// Lock releases when processing begins, not when it finishes
|
||||
}
|
||||
```
|
||||
|
||||
## Use Horizon for Complex Queue Scenarios
|
||||
|
||||
Use Laravel Horizon when you need monitoring, auto-scaling, failure tracking, or multiple queues with different priorities.
|
||||
|
||||
```php
|
||||
// config/horizon.php
|
||||
'environments' => [
|
||||
'production' => [
|
||||
'supervisor-1' => [
|
||||
'connection' => 'redis',
|
||||
'queue' => ['high', 'default', 'low'],
|
||||
'balance' => 'auto',
|
||||
'minProcesses' => 1,
|
||||
'maxProcesses' => 10,
|
||||
'tries' => 3,
|
||||
],
|
||||
],
|
||||
],
|
||||
```
|
||||
|
|
@ -1,99 +0,0 @@
|
|||
# Routing & Controllers Best Practices
|
||||
|
||||
## Use Implicit Route Model Binding
|
||||
|
||||
Let Laravel resolve models automatically from route parameters.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
public function show(int $id)
|
||||
{
|
||||
$post = Post::findOrFail($id);
|
||||
}
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
public function show(Post $post)
|
||||
{
|
||||
return view('posts.show', ['post' => $post]);
|
||||
}
|
||||
```
|
||||
|
||||
## Use Scoped Bindings for Nested Resources
|
||||
|
||||
Enforce parent-child relationships automatically.
|
||||
|
||||
```php
|
||||
Route::get('/users/{user}/posts/{post}', function (User $user, Post $post) {
|
||||
// $post is automatically scoped to $user
|
||||
})->scopeBindings();
|
||||
```
|
||||
|
||||
## Use Resource Controllers
|
||||
|
||||
Use `Route::resource()` or `apiResource()` for RESTful endpoints.
|
||||
|
||||
```php
|
||||
Route::resource('posts', PostController::class);
|
||||
// In routes/api.php — the /api prefix is applied automatically
|
||||
Route::apiResource('posts', Api\PostController::class);
|
||||
```
|
||||
|
||||
## Keep Controllers Thin
|
||||
|
||||
Aim for under 10 lines per method. Extract business logic to action or service classes.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
public function store(Request $request)
|
||||
{
|
||||
$validated = $request->validate([...]);
|
||||
if ($request->hasFile('image')) {
|
||||
$request->file('image')->move(public_path('images'));
|
||||
}
|
||||
$post = Post::create($validated);
|
||||
$post->tags()->sync($validated['tags']);
|
||||
event(new PostCreated($post));
|
||||
return redirect()->route('posts.show', $post);
|
||||
}
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
public function store(StorePostRequest $request, CreatePostAction $create)
|
||||
{
|
||||
$post = $create->execute($request->validated());
|
||||
|
||||
return redirect()->route('posts.show', $post);
|
||||
}
|
||||
```
|
||||
|
||||
## Type-Hint Form Requests
|
||||
|
||||
Type-hinting Form Requests triggers automatic validation and authorization before the method executes.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'title' => ['required', 'max:255'],
|
||||
'body' => ['required'],
|
||||
]);
|
||||
|
||||
Post::create($validated);
|
||||
|
||||
return redirect()->route('posts.index');
|
||||
}
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
public function store(StorePostRequest $request): RedirectResponse
|
||||
{
|
||||
Post::create($request->validated());
|
||||
|
||||
return redirect()->route('posts.index');
|
||||
}
|
||||
```
|
||||
|
|
@ -1,39 +0,0 @@
|
|||
# Task Scheduling Best Practices
|
||||
|
||||
## Use `withoutOverlapping()` on Variable-Duration Tasks
|
||||
|
||||
Without it, a long-running task spawns a second instance on the next tick, causing double-processing or resource exhaustion.
|
||||
|
||||
## Use `onOneServer()` on Multi-Server Deployments
|
||||
|
||||
Without it, every server runs the same task simultaneously. Requires a shared cache driver (Redis, database, Memcached).
|
||||
|
||||
## Use `runInBackground()` for Concurrent Long Tasks
|
||||
|
||||
By default, tasks at the same tick run sequentially. A slow first task delays all subsequent ones. `runInBackground()` runs them as separate processes.
|
||||
|
||||
## Use `environments()` to Restrict Tasks
|
||||
|
||||
Prevent accidental execution of production-only tasks (billing, reporting) on staging.
|
||||
|
||||
```php
|
||||
Schedule::command('billing:charge')->monthly()->environments(['production']);
|
||||
```
|
||||
|
||||
## Use `takeUntilTimeout()` for Time-Bounded Processing
|
||||
|
||||
A task running every 15 minutes that processes an unbounded cursor can overlap with the next run. Bound execution time.
|
||||
|
||||
## Use Schedule Groups for Shared Configuration
|
||||
|
||||
Avoid repeating `->onOneServer()->timezone('America/New_York')` across many tasks.
|
||||
|
||||
```php
|
||||
Schedule::daily()
|
||||
->onOneServer()
|
||||
->timezone('America/New_York')
|
||||
->group(function () {
|
||||
Schedule::command('emails:send --force');
|
||||
Schedule::command('emails:prune');
|
||||
});
|
||||
```
|
||||
|
|
@ -1,198 +0,0 @@
|
|||
# Security Best Practices
|
||||
|
||||
## Mass Assignment Protection
|
||||
|
||||
Every model must define `$fillable` (whitelist) or `$guarded` (blacklist).
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
class User extends Model
|
||||
{
|
||||
protected $guarded = []; // All fields are mass assignable
|
||||
}
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
class User extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'name',
|
||||
'email',
|
||||
'password',
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
Never use `$guarded = []` on models that accept user input.
|
||||
|
||||
## Authorize Every Action
|
||||
|
||||
Use policies or gates in controllers. Never skip authorization.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
public function update(UpdatePostRequest $request, Post $post)
|
||||
{
|
||||
$post->update($request->validated());
|
||||
}
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
public function update(UpdatePostRequest $request, Post $post)
|
||||
{
|
||||
Gate::authorize('update', $post);
|
||||
|
||||
$post->update($request->validated());
|
||||
}
|
||||
```
|
||||
|
||||
Or via Form Request:
|
||||
|
||||
```php
|
||||
public function authorize(): bool
|
||||
{
|
||||
return $this->user()->can('update', $this->route('post'));
|
||||
}
|
||||
```
|
||||
|
||||
## Prevent SQL Injection
|
||||
|
||||
Always use parameter binding. Never interpolate user input into queries.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
DB::select("SELECT * FROM users WHERE name = '{$request->name}'");
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
User::where('name', $request->name)->get();
|
||||
|
||||
// Raw expressions with bindings
|
||||
User::whereRaw('LOWER(name) = ?', [strtolower($request->name)])->get();
|
||||
```
|
||||
|
||||
## Escape Output to Prevent XSS
|
||||
|
||||
Use `{{ }}` for HTML escaping. Only use `{!! !!}` for trusted, pre-sanitized content.
|
||||
|
||||
Incorrect:
|
||||
```blade
|
||||
{!! $user->bio !!}
|
||||
```
|
||||
|
||||
Correct:
|
||||
```blade
|
||||
{{ $user->bio }}
|
||||
```
|
||||
|
||||
## CSRF Protection
|
||||
|
||||
Include `@csrf` in all POST/PUT/DELETE Blade forms. In Inertia apps, the `@csrf` directive is automatically applied.
|
||||
|
||||
Incorrect:
|
||||
```blade
|
||||
<form method="POST" action="/posts">
|
||||
<input type="text" name="title">
|
||||
</form>
|
||||
```
|
||||
|
||||
Correct:
|
||||
```blade
|
||||
<form method="POST" action="/posts">
|
||||
@csrf
|
||||
<input type="text" name="title">
|
||||
</form>
|
||||
```
|
||||
|
||||
## Rate Limit Auth and API Routes
|
||||
|
||||
Apply `throttle` middleware to authentication and API routes.
|
||||
|
||||
```php
|
||||
RateLimiter::for('login', function (Request $request) {
|
||||
return Limit::perMinute(5)->by($request->ip());
|
||||
});
|
||||
|
||||
Route::post('/login', LoginController::class)->middleware('throttle:login');
|
||||
```
|
||||
|
||||
## Validate File Uploads
|
||||
|
||||
Validate extension, MIME type, and size. The `mimes` rule checks extensions; use `mimetypes` for actual MIME type validation. Never trust client-provided filenames.
|
||||
|
||||
```php
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'avatar' => ['required', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048'],
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
Store with generated filenames:
|
||||
|
||||
```php
|
||||
$path = $request->file('avatar')->store('avatars', 'public');
|
||||
```
|
||||
|
||||
## Keep Secrets Out of Code
|
||||
|
||||
Never commit `.env`. Access secrets via `config()` only.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
$key = env('API_KEY');
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
// config/services.php
|
||||
'api_key' => env('API_KEY'),
|
||||
|
||||
// In application code
|
||||
$key = config('services.api_key');
|
||||
```
|
||||
|
||||
## Audit Dependencies
|
||||
|
||||
Run `composer audit` periodically to check for known vulnerabilities in dependencies. Automate this in CI to catch issues before deployment.
|
||||
|
||||
```bash
|
||||
composer audit
|
||||
```
|
||||
|
||||
## Encrypt Sensitive Database Fields
|
||||
|
||||
Use `encrypted` cast for API keys/tokens and mark the attribute as `hidden`.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
class Integration extends Model
|
||||
{
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'api_key' => 'string',
|
||||
];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
class Integration extends Model
|
||||
{
|
||||
protected $hidden = ['api_key', 'api_secret'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'api_key' => 'encrypted',
|
||||
'api_secret' => 'encrypted',
|
||||
];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
|
@ -1,125 +0,0 @@
|
|||
# Conventions & Style
|
||||
|
||||
## Follow Laravel Naming Conventions
|
||||
|
||||
| What | Convention | Good | Bad |
|
||||
|------|-----------|------|-----|
|
||||
| Controller | singular | `ArticleController` | `ArticlesController` |
|
||||
| Model | singular | `User` | `Users` |
|
||||
| Table | plural, snake_case | `article_comments` | `articleComments` |
|
||||
| Pivot table | singular alphabetical | `article_user` | `user_article` |
|
||||
| Column | snake_case, no model name | `meta_title` | `article_meta_title` |
|
||||
| Foreign key | singular model + `_id` | `article_id` | `articles_id` |
|
||||
| Route | plural | `articles/1` | `article/1` |
|
||||
| Route name | snake_case with dots | `users.show_active` | `users.show-active` |
|
||||
| Method | camelCase | `getAll` | `get_all` |
|
||||
| Variable | camelCase | `$articlesWithAuthor` | `$articles_with_author` |
|
||||
| Collection | descriptive, plural | `$activeUsers` | `$data` |
|
||||
| Object | descriptive, singular | `$activeUser` | `$users` |
|
||||
| View | kebab-case | `show-filtered.blade.php` | `showFiltered.blade.php` |
|
||||
| Config | snake_case | `google_calendar.php` | `googleCalendar.php` |
|
||||
| Enum | singular | `UserType` | `UserTypes` |
|
||||
|
||||
## Prefer Shorter Readable Syntax
|
||||
|
||||
| Verbose | Shorter |
|
||||
|---------|---------|
|
||||
| `Session::get('cart')` | `session('cart')` |
|
||||
| `$request->session()->get('cart')` | `session('cart')` |
|
||||
| `$request->input('name')` | `$request->name` |
|
||||
| `return Redirect::back()` | `return back()` |
|
||||
| `Carbon::now()` | `now()` |
|
||||
| `App::make('Class')` | `app('Class')` |
|
||||
| `->where('column', '=', 1)` | `->where('column', 1)` |
|
||||
| `->orderBy('created_at', 'desc')` | `->latest()` |
|
||||
| `->orderBy('created_at', 'asc')` | `->oldest()` |
|
||||
| `->first()->name` | `->value('name')` |
|
||||
|
||||
## Use Laravel String & Array Helpers
|
||||
|
||||
Laravel provides `Str`, `Arr`, `Number`, and `Uri` helper classes that are more readable, chainable, and UTF-8 safe than raw PHP functions. Always prefer them.
|
||||
|
||||
Strings — use `Str` and fluent `Str::of()` over raw PHP:
|
||||
```php
|
||||
// Incorrect
|
||||
$slug = strtolower(str_replace(' ', '-', $title));
|
||||
$short = substr($text, 0, 100) . '...';
|
||||
$class = substr(strrchr('App\Models\User', '\\'), 1);
|
||||
|
||||
// Correct
|
||||
$slug = Str::slug($title);
|
||||
$short = Str::limit($text, 100);
|
||||
$class = class_basename('App\Models\User');
|
||||
```
|
||||
|
||||
Fluent strings — chain operations for complex transformations:
|
||||
```php
|
||||
// Incorrect
|
||||
$result = strtolower(trim(str_replace('_', '-', $input)));
|
||||
|
||||
// Correct
|
||||
$result = Str::of($input)->trim()->replace('_', '-')->lower();
|
||||
```
|
||||
|
||||
Key `Str` methods to prefer: `Str::slug()`, `Str::limit()`, `Str::contains()`, `Str::before()`, `Str::after()`, `Str::between()`, `Str::camel()`, `Str::snake()`, `Str::kebab()`, `Str::headline()`, `Str::squish()`, `Str::mask()`, `Str::uuid()`, `Str::ulid()`, `Str::random()`, `Str::is()`.
|
||||
|
||||
Arrays — use `Arr` over raw PHP:
|
||||
```php
|
||||
// Incorrect
|
||||
$name = isset($array['user']['name']) ? $array['user']['name'] : 'default';
|
||||
|
||||
// Correct
|
||||
$name = Arr::get($array, 'user.name', 'default');
|
||||
```
|
||||
|
||||
Key `Arr` methods: `Arr::get()`, `Arr::has()`, `Arr::only()`, `Arr::except()`, `Arr::first()`, `Arr::flatten()`, `Arr::pluck()`, `Arr::where()`, `Arr::wrap()`.
|
||||
|
||||
Numbers — use `Number` for display formatting:
|
||||
```php
|
||||
Number::format(1000000); // "1,000,000"
|
||||
Number::currency(1500, 'USD'); // "$1,500.00"
|
||||
Number::abbreviate(1000000); // "1M"
|
||||
Number::fileSize(1024 * 1024); // "1 MB"
|
||||
Number::percentage(75.5); // "75.5%"
|
||||
```
|
||||
|
||||
URIs — use `Uri` for URL manipulation:
|
||||
```php
|
||||
$uri = Uri::of('https://example.com/search')
|
||||
->withQuery(['q' => 'laravel', 'page' => 1]);
|
||||
```
|
||||
|
||||
Use `$request->string('name')` to get a fluent `Stringable` directly from request input for immediate chaining.
|
||||
|
||||
Use `search-docs` for the full list of available methods — these helpers are extensive.
|
||||
|
||||
## No Inline JS/CSS in Blade
|
||||
|
||||
Do not put JS or CSS in Blade templates. Do not put HTML in PHP classes.
|
||||
|
||||
Incorrect:
|
||||
```blade
|
||||
let article = `{{ json_encode($article) }}`;
|
||||
```
|
||||
|
||||
Correct:
|
||||
```blade
|
||||
<button class="js-fav-article" data-article='@json($article)'>{{ $article->name }}</button>
|
||||
```
|
||||
|
||||
Pass data to JS via data attributes or use a dedicated PHP-to-JS package.
|
||||
|
||||
## No Unnecessary Comments
|
||||
|
||||
Code should be readable on its own. Use descriptive method and variable names instead of comments. The only exception is config files, where descriptive comments are expected.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
// Check if there are any joins
|
||||
if (count((array) $builder->getQuery()->joins) > 0)
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
if ($this->hasJoins())
|
||||
```
|
||||
|
|
@ -1,43 +0,0 @@
|
|||
# Testing Best Practices
|
||||
|
||||
## Use `LazilyRefreshDatabase` Over `RefreshDatabase`
|
||||
|
||||
`RefreshDatabase` migrates once per process and wraps each test in a rolled-back transaction. `LazilyRefreshDatabase` skips even that first migration if the schema is already up to date.
|
||||
|
||||
## Use Model Assertions Over Raw Database Assertions
|
||||
|
||||
Incorrect: `$this->assertDatabaseHas('users', ['id' => $user->id]);`
|
||||
|
||||
Correct: `$this->assertModelExists($user);`
|
||||
|
||||
More expressive, type-safe, and fails with clearer messages.
|
||||
|
||||
## Use Factory States and Sequences
|
||||
|
||||
Named states make tests self-documenting. Sequences eliminate repetitive setup.
|
||||
|
||||
Incorrect: `User::factory()->create(['email_verified_at' => null]);`
|
||||
|
||||
Correct: `User::factory()->unverified()->create();`
|
||||
|
||||
## Use `Exceptions::fake()` to Assert Exception Reporting
|
||||
|
||||
Instead of `withoutExceptionHandling()`, use `Exceptions::fake()` to assert the correct exception was reported while the request completes normally.
|
||||
|
||||
## Call `Event::fake()` After Factory Setup
|
||||
|
||||
Model factories rely on model events (e.g., `creating` to generate UUIDs). Calling `Event::fake()` before factory calls silences those events, producing broken models.
|
||||
|
||||
Incorrect: `Event::fake(); $user = User::factory()->create();`
|
||||
|
||||
Correct: `$user = User::factory()->create(); Event::fake();`
|
||||
|
||||
## Use `recycle()` to Share Relationship Instances Across Factories
|
||||
|
||||
Without `recycle()`, nested factories create separate instances of the same conceptual entity.
|
||||
|
||||
```php
|
||||
Ticket::factory()
|
||||
->recycle(Airline::factory()->create())
|
||||
->create();
|
||||
```
|
||||
|
|
@ -1,75 +0,0 @@
|
|||
# Validation & Forms Best Practices
|
||||
|
||||
## Use Form Request Classes
|
||||
|
||||
Extract validation from controllers into dedicated Form Request classes.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
public function store(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'title' => 'required|max:255',
|
||||
'body' => 'required',
|
||||
]);
|
||||
}
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
public function store(StorePostRequest $request)
|
||||
{
|
||||
Post::create($request->validated());
|
||||
}
|
||||
```
|
||||
|
||||
## Array vs. String Notation for Rules
|
||||
|
||||
Array syntax is more readable and composes cleanly with `Rule::` objects. Prefer it in new code, but check existing Form Requests first and match whatever notation the project already uses.
|
||||
|
||||
```php
|
||||
// Preferred for new code
|
||||
'email' => ['required', 'email', Rule::unique('users')],
|
||||
|
||||
// Follow existing convention if the project uses string notation
|
||||
'email' => 'required|email|unique:users',
|
||||
```
|
||||
|
||||
## Always Use `validated()`
|
||||
|
||||
Get only validated data. Never use `$request->all()` for mass operations.
|
||||
|
||||
Incorrect:
|
||||
```php
|
||||
Post::create($request->all());
|
||||
```
|
||||
|
||||
Correct:
|
||||
```php
|
||||
Post::create($request->validated());
|
||||
```
|
||||
|
||||
## Use `Rule::when()` for Conditional Validation
|
||||
|
||||
```php
|
||||
'company_name' => [
|
||||
Rule::when($this->account_type === 'business', ['required', 'string', 'max:255']),
|
||||
],
|
||||
```
|
||||
|
||||
## Use the `after()` Method for Custom Validation
|
||||
|
||||
Use `after()` instead of `withValidator()` for custom validation logic that depends on multiple fields.
|
||||
|
||||
```php
|
||||
public function after(): array
|
||||
{
|
||||
return [
|
||||
function (Validator $validator) {
|
||||
if ($this->quantity > Product::find($this->product_id)?->stock) {
|
||||
$validator->errors()->add('quantity', 'Not enough stock.');
|
||||
}
|
||||
},
|
||||
];
|
||||
}
|
||||
```
|
||||
|
|
@ -1,112 +0,0 @@
|
|||
---
|
||||
name: mcp-development
|
||||
description: "Use this skill for Laravel MCP development. Trigger when creating or editing MCP tools, resources, prompts, servers, or UI apps in Laravel projects. Covers: artisan make:mcp-* generators, routes/ai.php, Tool/Resource/Prompt/AppResource classes, schema validation, shouldRegister(), OAuth setup, URI templates, read-only attributes, MCP debugging, MCP UI apps, the x-mcp::app Blade component, createMcpApp(), default AppResource handle() auto-infers view from class name, Response::view(), AppMeta/Csp/Permissions/appMeta() configuration, #[RendersApp] attribute, Library enum for CDN libraries (Tailwind, Alpine), and host theming via CSS variables. Use this whenever the user mentions MCP apps, MCP UI, interactive MCP resources, styling MCP apps with Tailwind or Alpine, or building visual interfaces for AI agents."
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
|
||||
# MCP Development
|
||||
|
||||
## Documentation
|
||||
|
||||
Use `search-docs` for detailed Laravel MCP patterns and documentation.
|
||||
|
||||
For MCP UI apps (interactive HTML resources), read `references/app.md` — it covers the full architecture, host theming CSS variables, tool-to-UI linking patterns, library scripts (Tailwind, Alpine via `Library`), and real-world examples.
|
||||
|
||||
## Basic Usage
|
||||
|
||||
Register MCP servers in `routes/ai.php`:
|
||||
|
||||
<!-- Register MCP Server -->
|
||||
```php
|
||||
use Laravel\Mcp\Facades\Mcp;
|
||||
|
||||
Mcp::web();
|
||||
```
|
||||
|
||||
### Creating MCP Primitives
|
||||
|
||||
```bash
|
||||
php artisan make:mcp-tool ToolName # Create a tool
|
||||
|
||||
php artisan make:mcp-resource ResourceName # Create a resource
|
||||
|
||||
php artisan make:mcp-prompt PromptName # Create a prompt
|
||||
|
||||
php artisan make:mcp-server ServerName # Create a server
|
||||
|
||||
php artisan make:mcp-app-resource DashboardApp # Create a UI app (2 files)
|
||||
|
||||
```
|
||||
|
||||
After creating primitives, register them in your server's `$tools`, `$resources`, or `$prompts` properties.
|
||||
|
||||
### Tools
|
||||
|
||||
<!-- MCP Tool Example -->
|
||||
```php
|
||||
use Illuminate\Json\Schema\JsonSchema;
|
||||
use Laravel\Mcp\Request;
|
||||
use Laravel\Mcp\Response;
|
||||
use Laravel\Mcp\Server\Tool;
|
||||
|
||||
class MyTool extends Tool
|
||||
{
|
||||
protected string $description = 'Describe what this tool does';
|
||||
|
||||
public function schema(JsonSchema $schema): array
|
||||
{
|
||||
return [
|
||||
'name' => $schema->string()->description('The name parameter')->required(),
|
||||
];
|
||||
}
|
||||
|
||||
public function handle(Request $request): Response
|
||||
{
|
||||
$request->validate(['name' => 'required|string']);
|
||||
|
||||
return Response::text('Hello, '.$request->get('name'));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Registering Primitives in a Server
|
||||
|
||||
<!-- Register Primitives in MCP Server -->
|
||||
```php
|
||||
use Laravel\Mcp\Server;
|
||||
|
||||
class AppServer extends Server
|
||||
{
|
||||
protected array $tools = [
|
||||
\App\Mcp\Tools\MyTool::class,
|
||||
];
|
||||
|
||||
protected array $resources = [
|
||||
\App\Mcp\Resources\MyResource::class,
|
||||
];
|
||||
|
||||
protected array $prompts = [
|
||||
\App\Mcp\Prompts\MyPrompt::class,
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
## MCP UI Apps
|
||||
|
||||
For MCP UI apps, read `references/app.md` — it covers quick start examples, full architecture, AppMeta/Csp/Permissions, `#[RendersApp]` tool linking, library scripts (Tailwind/Alpine via `Library`), host theming CSS variables, and real-world patterns.
|
||||
|
||||
## Verification
|
||||
|
||||
1. Check `routes/ai.php` for proper registration
|
||||
2. Test tool via MCP client
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
- Running `mcp:start` command (it hangs waiting for input)
|
||||
- Using HTTPS locally with Node-based MCP clients
|
||||
- Not using `search-docs` for the latest MCP documentation
|
||||
- Not registering MCP server routes in `routes/ai.php`
|
||||
- Do not register `ai.php` in `bootstrap.php`; it is registered automatically
|
||||
- OAuth registration supports custom URI schemes (e.g., `cursor://`, `vscode://`) for native desktop clients via `mcp.custom_schemes` config
|
||||
|
|
@ -1,940 +0,0 @@
|
|||
# MCP UI Apps Reference
|
||||
|
||||
## Quick Start
|
||||
|
||||
`make:mcp-app-resource DashboardApp` generates two files — a PHP registration stub and a Blade view. The entire app lives in the Blade view.
|
||||
|
||||
**PHP class** — renders the Blade view. The view name is auto-inferred from the class name (`mcp.<kebab-class-name>`), so the generated stub needs no changes unless you're passing additional server-side data:
|
||||
|
||||
```php
|
||||
class DashboardApp extends AppResource
|
||||
{
|
||||
public function handle(Request $request): Response
|
||||
{
|
||||
return Response::view('mcp.dashboard-app', [
|
||||
'title' => $this->title(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Blade view** — HTML structure + inline JS, everything in one file:
|
||||
|
||||
```blade
|
||||
<x-mcp::app title="Dashboard App">
|
||||
<x-slot:head>
|
||||
<script type="module">
|
||||
createMcpApp(async (app) => {
|
||||
document.getElementById('run-btn').addEventListener('click', async () => {
|
||||
const result = await app.callServerTool({ name: 'tool-name', arguments: {} });
|
||||
document.getElementById('output').textContent = result.content[0]?.text ?? '';
|
||||
});
|
||||
});
|
||||
</script>
|
||||
</x-slot:head>
|
||||
|
||||
<div id="app">
|
||||
<h1>Dashboard App</h1>
|
||||
<button id="run-btn">Run</button>
|
||||
<p id="output"></p>
|
||||
</div>
|
||||
</x-mcp::app>
|
||||
```
|
||||
|
||||
`createMcpApp` is a global pre-bundled by the package — no npm install, no imports, no Vite required. It handles connection, error handling, and host theming automatically.
|
||||
|
||||
---
|
||||
|
||||
## Core Concept: Tool + Resource
|
||||
|
||||
Every MCP App is built from two parts linked together:
|
||||
|
||||
- **Tool** — called by the LLM or host. Returns a text/data response and tells the host which UI resource to render via `_meta.ui.resourceUri`.
|
||||
- **AppResource** — serves the self-contained HTML app. The host fetches it after the tool is called and renders it in a sandboxed iframe.
|
||||
|
||||
```
|
||||
LLM calls Tool
|
||||
└─► Tool response includes _meta.ui.resourceUri → "ui://dashboard-app"
|
||||
└─► Host fetches AppResource at that URI
|
||||
└─► Host renders HTML in sandboxed iframe
|
||||
└─► createMcpApp() connects the iframe back to the server
|
||||
└─► UI calls app-only tools to load/refresh data
|
||||
```
|
||||
|
||||
The link is declared once with `#[RendersApp]` on the tool:
|
||||
|
||||
```php
|
||||
#[RendersApp(resource: DashboardApp::class)]
|
||||
class ShowDashboard extends Tool
|
||||
{
|
||||
public function handle(Request $request): Response
|
||||
{
|
||||
return Response::text('Dashboard loaded.');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
After that, the host handles fetching and rendering the resource automatically — you never reference the URI by hand.
|
||||
|
||||
---
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
MCP Apps add interactive UI to the Model Context Protocol. The server returns self-contained HTML with all JS/CSS inlined. The host renders it in a sandboxed iframe. Apps communicate back via `createMcpApp()` — a pre-bundled global implementing the MCP UI PostMessage protocol.
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────┐
|
||||
│ Host (Claude, ChatGPT, VS Code) │
|
||||
│ ┌───────────────────────────────────────┐ │
|
||||
│ │ Sandboxed iframe │ │
|
||||
│ │ ┌─────────────────────────────────┐ │ │
|
||||
│ │ │ Your MCP App (HTML/JS/CSS) │ │ │
|
||||
│ │ │ - Rendered by AppResource │ │ │
|
||||
│ │ │ - Single self-contained HTML │ │ │
|
||||
│ │ │ - Themed via host CSS vars │ │ │
|
||||
│ │ └─────────────────────────────────┘ │ │
|
||||
│ └───────────────────────────────────────┘ │
|
||||
└──────────────────┬──────────────────────────┘
|
||||
│ MCP Protocol (JSON-RPC)
|
||||
┌──────────────────▼──────────────────────────┐
|
||||
│ Laravel MCP Server │
|
||||
│ - AppResource → self-contained HTML │
|
||||
│ - Tool #[RendersApp] → triggers UI display │
|
||||
│ - resources/read → serves HTML + _meta.ui │
|
||||
└─────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
The server automatically advertises `io.modelcontextprotocol/ui` capability when any `AppResource` is registered. The client declares support in `capabilities.extensions["io.modelcontextprotocol/ui"]` during the initialize handshake.
|
||||
|
||||
---
|
||||
|
||||
## Server-Side
|
||||
|
||||
Minimal case — `handle()` renders the Blade view, entire app lives there:
|
||||
|
||||
```php
|
||||
class DashboardApp extends AppResource
|
||||
{
|
||||
public function handle(Request $request): Response
|
||||
{
|
||||
return Response::view('mcp.dashboard-app', [
|
||||
'title' => $this->title(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Auto-renders `resources/views/mcp/dashboard-app.blade.php` with `$title` available via `$this->title()`.
|
||||
|
||||
Override `handle()` only when passing additional server-side data:
|
||||
|
||||
```php
|
||||
class AnalyticsDashboard extends AppResource
|
||||
{
|
||||
public function handle(Request $request): Response
|
||||
{
|
||||
return Response::view('mcp.analytics-dashboard', [
|
||||
'title' => $this->title(),
|
||||
'metrics' => Metric::latest()->take(10)->get(),
|
||||
'totalUsers' => User::count(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`Response::view($view, $data = [], $mergeData = [])` renders a Blade view and returns it as text.
|
||||
|
||||
`Response::html($path)` reads an HTML file from disk and returns its content. Relative paths resolve via `resource_path()`:
|
||||
|
||||
```php
|
||||
class StaticApp extends AppResource
|
||||
{
|
||||
public function handle(Request $request): Response
|
||||
{
|
||||
return Response::html('mcp/static-app.html');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### AppMeta Configuration
|
||||
|
||||
The simplest way to configure UI metadata is via the `#[AppMeta]` attribute directly on your resource class:
|
||||
|
||||
```php
|
||||
use Laravel\Mcp\Server\Attributes\AppMeta;
|
||||
use Laravel\Mcp\Server\Ui\Enums\Library;
|
||||
use Laravel\Mcp\Server\Ui\Enums\Permission;
|
||||
|
||||
#[AppMeta(
|
||||
connectDomains: ['https://api.stripe.com'],
|
||||
permissions: [Permission::Camera, Permission::ClipboardWrite],
|
||||
prefersBorder: true,
|
||||
libraries: [Library::Tailwind, Library::Alpine],
|
||||
)]
|
||||
class PaymentsResource extends AppResource
|
||||
{
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
For dynamic or computed configuration, override `appMeta()` instead:
|
||||
|
||||
```php
|
||||
use Laravel\Mcp\Server\Ui\AppMeta;
|
||||
|
||||
public function appMeta(): AppMeta
|
||||
{
|
||||
return AppMeta::make()
|
||||
->csp(Csp::make()->connectDomains(config('services.api.domains')))
|
||||
->permissions(Permissions::make()->allow(Permission::Camera))
|
||||
->libraries(Library::Tailwind)
|
||||
->domain('sandbox.example.com');
|
||||
}
|
||||
```
|
||||
|
||||
#### Permission Enum
|
||||
|
||||
Use the `Permission` enum for type-safe permission configuration:
|
||||
|
||||
```php
|
||||
use Laravel\Mcp\Server\Ui\Enums\Permission;
|
||||
|
||||
Permission::Camera // 'camera'
|
||||
Permission::Microphone // 'microphone'
|
||||
Permission::Geolocation // 'geolocation'
|
||||
Permission::ClipboardWrite // 'clipboardWrite'
|
||||
```
|
||||
|
||||
#### Csp
|
||||
|
||||
Controls what external domains the iframe can access:
|
||||
|
||||
```php
|
||||
Csp::make()
|
||||
->connectDomains(['https://api.example.com']) // fetch, XHR, WebSocket origins
|
||||
->resourceDomains(['https://cdn.example.com']) // images, scripts, fonts, media
|
||||
->frameDomains(['https://embed.example.com']) // nested iframe origins
|
||||
->baseUriDomains(['https://base.example.com']); // base URI origins
|
||||
```
|
||||
|
||||
#### Permissions
|
||||
|
||||
```php
|
||||
Permissions::make()->allow(Permission::Camera, Permission::ClipboardWrite);
|
||||
|
||||
Permissions::make()
|
||||
->camera()
|
||||
->microphone()
|
||||
->geolocation()
|
||||
->clipboardWrite();
|
||||
```
|
||||
|
||||
Each enabled permission serializes as `"camera": {}` per the MCP spec.
|
||||
|
||||
#### AppMeta
|
||||
|
||||
```php
|
||||
AppMeta::make()
|
||||
->csp(Csp::make()->connectDomains([...]))
|
||||
->permissions(Permissions::make()->allow(Permission::Camera))
|
||||
->libraries(Library::Tailwind, Library::Alpine)
|
||||
->domain('sandbox.example.com') // dedicated sandbox origin (OAuth/CORS)
|
||||
->prefersBorder(false);
|
||||
```
|
||||
|
||||
`prefersBorder` defaults to `true`. `toArray()` omits null fields and empty nested objects. Library CDN domains are automatically merged into `csp.resourceDomains`.
|
||||
|
||||
#### domain
|
||||
|
||||
The `domain` field provides a stable origin that external APIs can allowlist for CORS. It is automatically resolved from `config('app.url')` (your `APP_URL` env variable) via `resolvedAppMeta()`, so most apps need no configuration. Override only when a resource needs a different origin:
|
||||
|
||||
```php
|
||||
#[AppMeta(domain: 'custom.example.com')]
|
||||
class PaymentsResource extends AppResource
|
||||
{
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
#### Library Scripts
|
||||
|
||||
The `libraries` parameter adds pre-configured CDN scripts to the `<head>` of your app. Available libraries:
|
||||
|
||||
```php
|
||||
use Laravel\Mcp\Server\Ui\Enums\Library;
|
||||
|
||||
Library::Tailwind // Tailwind CSS CDN + dark mode config
|
||||
Library::Alpine // Alpine.js CDN + x-cloak style
|
||||
```
|
||||
|
||||
When libraries are specified, the package automatically:
|
||||
|
||||
1. Injects the CDN `<script>` tags into the Blade view's `<head>` (after the MCP SDK, before your `<x-slot:head>`)
|
||||
2. Merges each library's CDN domains into `csp.resourceDomains` so the host allows loading them
|
||||
|
||||
Via attribute:
|
||||
|
||||
```php
|
||||
#[AppMeta(libraries: [Library::Tailwind])]
|
||||
class StyledApp extends AppResource
|
||||
{
|
||||
// Tailwind is available in the Blade view — no extra setup
|
||||
}
|
||||
```
|
||||
|
||||
Via fluent builder:
|
||||
|
||||
```php
|
||||
public function appMeta(): AppMeta
|
||||
{
|
||||
return AppMeta::make()
|
||||
->libraries(Library::Tailwind, Library::Alpine);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## View Layer
|
||||
|
||||
### `<x-mcp::app>` Blade Component
|
||||
|
||||
Renders a complete self-contained HTML document with the MCP SDK inlined. `createMcpApp` is available globally.
|
||||
|
||||
```blade
|
||||
<x-mcp::app title="Dashboard App">
|
||||
<x-slot:head>
|
||||
<script type="module">
|
||||
createMcpApp(async (app) => {
|
||||
document.getElementById('run-btn').addEventListener('click', async () => {
|
||||
const result = await app.callServerTool({ name: 'tool-name', arguments: {} });
|
||||
document.getElementById('output').textContent = result.content[0]?.text ?? '';
|
||||
});
|
||||
});
|
||||
</script>
|
||||
</x-slot:head>
|
||||
|
||||
<div id="app">
|
||||
<button id="run-btn">Run</button>
|
||||
<p id="output"></p>
|
||||
</div>
|
||||
</x-mcp::app>
|
||||
```
|
||||
|
||||
**Props and slots:**
|
||||
|
||||
| Name | Type | Description |
|
||||
| ------------- | ------------- | ---------------------------------------------------- |
|
||||
| `title` | Prop | Sets `<title>`. Optional. |
|
||||
| `head` | Named slot | Injected into `<head>` after the inlined SDK script. |
|
||||
| Default slot | Slot | Body content. |
|
||||
| `$attributes` | Attribute bag | Forwarded to `<body>` (e.g. `class="dark"`). |
|
||||
|
||||
The SDK is loaded from the `mcp.sdk` singleton (registered by `McpServiceProvider`) and inlined directly in a `<script>` tag. Library scripts (Tailwind, Alpine) configured via `#[AppMeta]` are injected after the SDK and before the `head` slot.
|
||||
|
||||
Publish the component: `php artisan vendor:publish --tag=mcp-views`.
|
||||
|
||||
To pass server-side data to JS, embed it as `data-*` attributes:
|
||||
|
||||
```blade
|
||||
<div id="app" data-users="{{ $users->toJson() }}">
|
||||
...
|
||||
</div>
|
||||
```
|
||||
|
||||
```js
|
||||
const users = JSON.parse(document.getElementById("app").dataset.users);
|
||||
```
|
||||
|
||||
## Client-Side
|
||||
|
||||
This package provides a simple MCP client library to easily work with client interactions.
|
||||
|
||||
### createMcpApp
|
||||
|
||||
Pre-bundled and inlined automatically — no npm install or imports required.
|
||||
|
||||
```js
|
||||
createMcpApp(async (app) => {
|
||||
// app is ready — connection established, theming applied
|
||||
});
|
||||
```
|
||||
|
||||
### Tools
|
||||
|
||||
#### app.callServerTool()
|
||||
|
||||
Accepts an object or positional arguments:
|
||||
|
||||
```js
|
||||
// Object form
|
||||
const result = await app.callServerTool({ name: 'get-analytics', arguments: { dateRange: '7d' } });
|
||||
|
||||
// Positional form
|
||||
const result = await app.callServerTool('get-analytics', { dateRange: '7d' });
|
||||
|
||||
// result structure depends on the server's tool response
|
||||
const text = result.content[0]?.text ?? "";
|
||||
```
|
||||
|
||||
All tool results share a standard structure:
|
||||
|
||||
| Property | Type | Description |
|
||||
| --------- | --------- | ------------------------------------------------------------------------- |
|
||||
| `content` | `Array` | Content items returned by the tool (each has `type` and `text` or `data`) |
|
||||
| `isError` | `boolean` | `true` when the tool returned an error response |
|
||||
|
||||
Always check `result.isError` before consuming `content`. See [Error Handling](#error-handling) for a full example.
|
||||
|
||||
### Resources
|
||||
|
||||
#### app.listResources()
|
||||
|
||||
```js
|
||||
const resources = await app.listResources();
|
||||
// or with cursor for pagination
|
||||
const resources = await app.listResources("cursor-value");
|
||||
// or object form
|
||||
const resources = await app.listResources({ cursor: "cursor-value" });
|
||||
```
|
||||
|
||||
#### app.readResource()
|
||||
|
||||
```js
|
||||
const resource = await app.readResource("ui://my-resource");
|
||||
// or object form
|
||||
const resource = await app.readResource({ uri: "ui://my-resource" });
|
||||
```
|
||||
|
||||
### Messaging
|
||||
|
||||
#### app.sendMessage()
|
||||
|
||||
Send a message to the model (creates a conversation turn):
|
||||
|
||||
```js
|
||||
// Object form with structured content
|
||||
await app.sendMessage({
|
||||
role: "user",
|
||||
content: [{ type: "text", text: "User submitted the form." }],
|
||||
});
|
||||
|
||||
// Shorthand — plain string content with optional role (defaults to 'user')
|
||||
await app.sendMessage("User submitted the form.");
|
||||
await app.sendMessage("System event occurred.", "user");
|
||||
```
|
||||
|
||||
### Host Context
|
||||
|
||||
#### app.getHostContext()
|
||||
|
||||
Returns the current host context, including theme and style variables:
|
||||
|
||||
```js
|
||||
const ctx = app.getHostContext();
|
||||
ctx?.theme; // 'light' | 'dark'
|
||||
ctx?.styles?.variables; // CSS variable map from host
|
||||
ctx?.styles?.css?.fonts; // font CSS from host
|
||||
```
|
||||
|
||||
#### app.getHostInfo()
|
||||
|
||||
```js
|
||||
const info = app.getHostInfo();
|
||||
```
|
||||
|
||||
#### app.getHostCapabilities()
|
||||
|
||||
```js
|
||||
const caps = app.getHostCapabilities();
|
||||
```
|
||||
|
||||
### Navigation & Files
|
||||
|
||||
#### app.openLink()
|
||||
|
||||
```js
|
||||
await app.openLink("https://example.com");
|
||||
// or object form
|
||||
await app.openLink({ url: "https://example.com" });
|
||||
```
|
||||
|
||||
#### app.downloadFile()
|
||||
|
||||
```js
|
||||
await app.downloadFile("file contents here");
|
||||
// or object form
|
||||
await app.downloadFile({ contents: "file contents here" });
|
||||
```
|
||||
|
||||
### Display
|
||||
|
||||
#### app.requestDisplayMode()
|
||||
|
||||
```js
|
||||
await app.requestDisplayMode("fullscreen");
|
||||
// or object form
|
||||
await app.requestDisplayMode({ mode: "fullscreen" });
|
||||
```
|
||||
|
||||
#### app.resize() / app.autoResize()
|
||||
|
||||
`resize()` sends a one-time size notification. `autoResize()` uses `ResizeObserver` to continuously notify the host of size changes. It returns a cleanup function that disconnects the observer — useful if you need to stop observing before teardown. The observer is also automatically disconnected on teardown.
|
||||
|
||||
```js
|
||||
const stopObserving = app.autoResize();
|
||||
|
||||
// Later, if needed:
|
||||
stopObserving();
|
||||
```
|
||||
|
||||
### Model Context
|
||||
|
||||
#### app.updateModelContext()
|
||||
|
||||
```js
|
||||
await app.updateModelContext({ key: "value" });
|
||||
```
|
||||
|
||||
### Lifecycle
|
||||
|
||||
#### app.requestTeardown()
|
||||
|
||||
Sends a teardown notification to the host.
|
||||
|
||||
```js
|
||||
app.requestTeardown();
|
||||
```
|
||||
|
||||
### Logging
|
||||
|
||||
#### app.sendLog()
|
||||
|
||||
```js
|
||||
// Positional form
|
||||
await app.sendLog("info", "Processing started", "my-logger");
|
||||
|
||||
// Object form
|
||||
await app.sendLog({
|
||||
level: "info",
|
||||
data: "Processing started",
|
||||
logger: "my-logger",
|
||||
});
|
||||
```
|
||||
|
||||
### Event Handlers
|
||||
|
||||
Register callbacks for host-side events. Tool input/result/cancelled events are queued until a handler is registered, then flushed.
|
||||
|
||||
```js
|
||||
createMcpApp(async (app) => {
|
||||
app.onToolInput((params) => {
|
||||
/* tool input received */
|
||||
});
|
||||
app.onToolInputPartial((params) => {
|
||||
/* partial tool input */
|
||||
});
|
||||
app.onToolResult((params) => {
|
||||
/* tool result received */
|
||||
});
|
||||
app.onToolCancelled((params) => {
|
||||
/* tool was cancelled */
|
||||
});
|
||||
app.onHostContextChanged((ctx) => {
|
||||
/* theme/styles changed */
|
||||
});
|
||||
app.onTeardown(async () => {
|
||||
/* cleanup before teardown */
|
||||
});
|
||||
app.onCallTool(async (params) => {
|
||||
/* host requests tool call */
|
||||
});
|
||||
app.onListTools(async (params) => {
|
||||
/* host requests tool list */
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Host Theming
|
||||
|
||||
`createMcpApp` automatically applies host theming on connect and on context change:
|
||||
|
||||
- Sets `data-theme` attribute and `color-scheme` on `<html>`
|
||||
- Applies CSS variables from `hostContext.styles.variables` to `:root`
|
||||
- Injects font CSS from `hostContext.styles.css.fonts` into a `<style>` tag
|
||||
|
||||
The specific CSS variables available depend on the host. Always provide fallback values — use `light-dark()` for theme-aware defaults:
|
||||
|
||||
```css
|
||||
:root {
|
||||
--color-background-primary: light-dark(#ffffff, #171717);
|
||||
--color-text-primary: light-dark(#171717, #fafafa);
|
||||
--color-text-secondary: light-dark(#525252, #a3a3a3);
|
||||
--color-border-primary: light-dark(#e5e5e5, #404040);
|
||||
--font-sans: system-ui, -apple-system, sans-serif;
|
||||
--border-radius-md: 8px;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: var(--font-sans);
|
||||
background: var(--color-background-primary);
|
||||
color: var(--color-text-primary);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.card {
|
||||
background: var(--color-background-secondary);
|
||||
border: 1px solid var(--color-border-primary);
|
||||
border-radius: var(--border-radius-md);
|
||||
padding: 1rem;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Tool-to-UI Linking
|
||||
|
||||
### #[RendersApp] Attribute
|
||||
|
||||
Associates a Tool with a UI Resource. When the tool is called, the host fetches and renders the linked resource.
|
||||
|
||||
```php
|
||||
use Laravel\Mcp\Server\Attributes\RendersApp;
|
||||
use Laravel\Mcp\Server\Ui\Enums\Visibility;
|
||||
|
||||
// Both model and app can call this tool (default)
|
||||
#[RendersApp(resource: DashboardApp::class)]
|
||||
class ShowDashboard extends Tool { ... }
|
||||
|
||||
// Only the app can call this tool (private to the UI)
|
||||
#[RendersApp(resource: DashboardApp::class, visibility: [Visibility::App])]
|
||||
class RefreshDashboardData extends Tool { ... }
|
||||
```
|
||||
|
||||
**Visibility:**
|
||||
|
||||
The `Visibility` enum (`Laravel\Mcp\Server\Ui\Enums\Visibility`) has two cases: `Model` and `App`. The default is `[Visibility::Model, Visibility::App]`.
|
||||
|
||||
| Visibility | Model | App | Use case |
|
||||
| -------------------------------------- | ----- | --- | ------------------------------------------------------ |
|
||||
| `[Visibility::Model, Visibility::App]` | Yes | Yes | Primary tools that trigger UI display |
|
||||
| `[Visibility::App]` | No | Yes | Backend actions the UI calls (refresh, save, paginate) |
|
||||
| `[Visibility::Model]` | Yes | No | Model-only tools linked to a UI |
|
||||
|
||||
### Primary + Private Pattern
|
||||
|
||||
```php
|
||||
#[RendersApp(resource: DashboardApp::class)]
|
||||
class ShowDashboard extends Tool
|
||||
{
|
||||
public function handle(Request $request): Response
|
||||
{
|
||||
return Response::text('Dashboard loaded.');
|
||||
}
|
||||
}
|
||||
|
||||
#[RendersApp(resource: DashboardApp::class, visibility: [Visibility::App])]
|
||||
class GetDashboardMetrics extends Tool
|
||||
{
|
||||
public function handle(Request $request): Response
|
||||
{
|
||||
return Response::json(Metric::latest()->take(50)->get());
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Testing
|
||||
|
||||
```php
|
||||
it('returns html content', function () {
|
||||
MyServer::readResource(DashboardApp::class)
|
||||
->assertSee('<div id="app">');
|
||||
});
|
||||
|
||||
it('has correct mime type and uri scheme', function () {
|
||||
$resource = new DashboardApp;
|
||||
$data = $resource->toArray();
|
||||
|
||||
expect($data['mimeType'])->toBe('text/html;profile=mcp-app')
|
||||
->and($data['_meta']['ui'])->toBeArray()
|
||||
->and($resource->uri())->toStartWith('ui://');
|
||||
});
|
||||
|
||||
it('configures ui meta correctly', function () {
|
||||
$meta = (new DashboardApp)->resolvedAppMeta();
|
||||
|
||||
expect($meta['csp']['connectDomains'])->toContain('https://api.example.com')
|
||||
->and($meta['permissions'])->toHaveKey('clipboardWrite');
|
||||
});
|
||||
|
||||
it('includes ui metadata in tool listing', function () {
|
||||
MyServer::listTools()->assertSee('show-dashboard');
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Patterns
|
||||
|
||||
### Real-time Polling
|
||||
|
||||
Use app-only tools to fetch fresh data at regular intervals from the UI:
|
||||
|
||||
```php
|
||||
#[RendersApp(resource: MonitorApp::class, visibility: [Visibility::App])]
|
||||
class GetMonitorData extends Tool
|
||||
{
|
||||
protected string $description = 'Fetch latest monitor metrics';
|
||||
|
||||
public function handle(Request $request): Response
|
||||
{
|
||||
return Response::json([
|
||||
'cpu' => sys_getloadavg()[0],
|
||||
'memory' => memory_get_usage(true),
|
||||
'timestamp' => now()->toISOString(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
createMcpApp(async (app) => {
|
||||
async function poll() {
|
||||
const result = await app.callServerTool('get-monitor-data');
|
||||
const data = JSON.parse(result.content[0]?.text ?? '{}');
|
||||
document.getElementById('cpu').textContent = data.cpu;
|
||||
}
|
||||
|
||||
setInterval(poll, 2000);
|
||||
poll();
|
||||
});
|
||||
```
|
||||
|
||||
### Chunked Data Loading
|
||||
|
||||
For large datasets, implement pagination via app-only tools:
|
||||
|
||||
```php
|
||||
#[RendersApp(resource: LogViewerApp::class, visibility: [Visibility::App])]
|
||||
class GetLogChunk extends Tool
|
||||
{
|
||||
protected string $description = 'Fetch a chunk of log entries';
|
||||
|
||||
public function schema(JsonSchema $schema): array
|
||||
{
|
||||
return [
|
||||
'offset' => $schema->integer()->description('Byte offset to start from')->required(),
|
||||
'limit' => $schema->integer()->description('Max bytes to return'),
|
||||
];
|
||||
}
|
||||
|
||||
public function handle(Request $request): Response
|
||||
{
|
||||
$request->validate(['offset' => 'required|integer', 'limit' => 'integer']);
|
||||
|
||||
$offset = $request->get('offset');
|
||||
$limit = $request->get('limit', 500_000);
|
||||
$content = Storage::get('logs/app.log');
|
||||
$chunk = substr($content, $offset, $limit);
|
||||
|
||||
return Response::json([
|
||||
'data' => $chunk,
|
||||
'offset' => $offset,
|
||||
'totalBytes' => strlen($content),
|
||||
'hasMore' => ($offset + $limit) < strlen($content),
|
||||
]);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Binary Resource Serving
|
||||
|
||||
Deliver images and binary content through MCP resources using `Response::blob()`:
|
||||
|
||||
```php
|
||||
#[RendersApp(resource: GalleryApp::class, visibility: [Visibility::App])]
|
||||
class GetImage extends Tool
|
||||
{
|
||||
protected string $description = 'Fetch an image by ID';
|
||||
|
||||
public function handle(Request $request): Response
|
||||
{
|
||||
$request->validate(['id' => 'required|integer']);
|
||||
|
||||
$image = Image::findOrFail($request->get('id'));
|
||||
$data = base64_encode(Storage::get($image->path));
|
||||
|
||||
return Response::blob($data);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In the client, convert the base64 blob to a data URI for rendering:
|
||||
|
||||
```js
|
||||
const result = await app.callServerTool('get-image', { id: 42 });
|
||||
const blob = result.content[0];
|
||||
img.src = `data:${blob.mimeType};base64,${blob.data}`;
|
||||
```
|
||||
|
||||
### Streaming Argument Previews
|
||||
|
||||
Use `onToolInputPartial` to show previews as the model streams tool arguments:
|
||||
|
||||
```js
|
||||
createMcpApp(async (app) => {
|
||||
app.onToolInputPartial((params) => {
|
||||
try {
|
||||
const partial = JSON.parse(params.arguments);
|
||||
if (partial.query) {
|
||||
document.getElementById("preview").textContent = partial.query;
|
||||
}
|
||||
} catch {
|
||||
// partial JSON — ignore until parseable
|
||||
}
|
||||
});
|
||||
|
||||
app.onToolResult((params) => {
|
||||
const data = JSON.parse(params.result.content[0]?.text ?? "{}");
|
||||
renderResults(data);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### View State Persistence
|
||||
|
||||
Use `localStorage` to preserve UI state across re-renders. For important state, persist server-side via an app-only tool:
|
||||
|
||||
```js
|
||||
createMcpApp(async (app) => {
|
||||
const STATE_KEY = "dashboard-view-state";
|
||||
|
||||
// Restore from localStorage
|
||||
const saved = JSON.parse(localStorage.getItem(STATE_KEY) || "{}");
|
||||
if (saved.activeTab) selectTab(saved.activeTab);
|
||||
|
||||
// Save on interaction
|
||||
function saveState(state) {
|
||||
localStorage.setItem(STATE_KEY, JSON.stringify(state));
|
||||
}
|
||||
|
||||
// For durable state, persist server-side
|
||||
async function saveServerState(state) {
|
||||
await app.callServerTool('save-dashboard-state', { state: JSON.stringify(state) });
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### Fullscreen Toggling
|
||||
|
||||
Switch between inline and fullscreen display modes and react to mode changes:
|
||||
|
||||
```js
|
||||
createMcpApp(async (app) => {
|
||||
document.getElementById("expand-btn").addEventListener("click", () => {
|
||||
app.requestDisplayMode("fullscreen");
|
||||
});
|
||||
|
||||
app.onHostContextChanged((ctx) => {
|
||||
document.body.classList.toggle(
|
||||
"fullscreen",
|
||||
ctx.displayMode === "fullscreen",
|
||||
);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### Model Context Updates
|
||||
|
||||
Keep the model informed about what the user is viewing so it can provide relevant assistance:
|
||||
|
||||
```js
|
||||
createMcpApp(async (app) => {
|
||||
async function notifyContext(view, detail) {
|
||||
await app.updateModelContext({
|
||||
currentView: view,
|
||||
detail: detail,
|
||||
});
|
||||
}
|
||||
|
||||
// Notify on tab change
|
||||
document.querySelectorAll(".tab").forEach((tab) => {
|
||||
tab.addEventListener("click", () => {
|
||||
notifyContext(tab.dataset.view, { filters: getActiveFilters() });
|
||||
});
|
||||
});
|
||||
|
||||
// For large payloads, follow up with sendMessage
|
||||
await app.updateModelContext({ currentView: "report", rows: 5000 });
|
||||
await app.sendMessage("The user is viewing a report with 5000 rows.");
|
||||
});
|
||||
```
|
||||
|
||||
### Pause Offscreen Views
|
||||
|
||||
Conserve resources by pausing animations and polling when the view is not visible:
|
||||
|
||||
```js
|
||||
createMcpApp(async (app) => {
|
||||
let pollInterval = null;
|
||||
|
||||
function startPolling() {
|
||||
if (!pollInterval) {
|
||||
pollInterval = setInterval(fetchData, 2000);
|
||||
}
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
clearInterval(pollInterval);
|
||||
pollInterval = null;
|
||||
}
|
||||
|
||||
const observer = new IntersectionObserver(([entry]) => {
|
||||
entry.isIntersecting ? startPolling() : stopPolling();
|
||||
});
|
||||
|
||||
observer.observe(document.documentElement);
|
||||
startPolling();
|
||||
});
|
||||
```
|
||||
|
||||
### Error Handling
|
||||
|
||||
Return `Response::error()` from tools and use `updateModelContext()` to signal degraded state:
|
||||
|
||||
```php
|
||||
class ProcessData extends Tool
|
||||
{
|
||||
public function handle(Request $request): Response
|
||||
{
|
||||
$request->validate(['input' => 'required|string']);
|
||||
|
||||
if (strlen($request->get('input')) > 10_000) {
|
||||
return Response::error('Input exceeds 10KB limit.');
|
||||
}
|
||||
|
||||
return Response::json(process($request->get('input')));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
createMcpApp(async (app) => {
|
||||
const result = await app.callServerTool('process-data', { input: value });
|
||||
|
||||
if (result.isError) {
|
||||
document.getElementById("error").textContent =
|
||||
result.content[0]?.text ?? "Unknown error";
|
||||
await app.updateModelContext({
|
||||
state: "error",
|
||||
message: result.content[0]?.text,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
renderOutput(JSON.parse(result.content[0]?.text ?? "{}"));
|
||||
});
|
||||
```
|
||||
|
|
@ -1,106 +0,0 @@
|
|||
---
|
||||
name: medialibrary-development
|
||||
description: Build and work with spatie/laravel-medialibrary features including associating files with Eloquent models, defining media collections and conversions, generating responsive images, and retrieving media URLs and paths.
|
||||
license: MIT
|
||||
metadata:
|
||||
author: Spatie
|
||||
---
|
||||
|
||||
# Media Library Development
|
||||
|
||||
## Overview
|
||||
|
||||
Use spatie/laravel-medialibrary to associate files with Eloquent models. Supports image/video conversions, responsive images, multiple collections, and various storage disks.
|
||||
|
||||
## When to Activate
|
||||
|
||||
- Activate when working with file uploads, media attachments, or image processing in Laravel.
|
||||
- Activate when code references `HasMedia`, `InteractsWithMedia`, the `Media` model, or media collections/conversions.
|
||||
- Activate when the user wants to add, retrieve, convert, or manage files attached to Eloquent models.
|
||||
|
||||
## Scope
|
||||
|
||||
- In scope: media uploads, collections, conversions, responsive images, custom properties, file retrieval, path/URL generation.
|
||||
- Out of scope: general file storage without Eloquent association, non-Laravel frameworks.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Identify the task (model setup, adding media, defining conversions, retrieving files, etc.).
|
||||
2. Read `references/medialibrary-guide.md` and focus on the relevant section.
|
||||
3. Apply the patterns from the reference, keeping code minimal and Laravel-native.
|
||||
|
||||
## Core Concepts
|
||||
|
||||
### Model Setup
|
||||
|
||||
Every model that should have media must implement `HasMedia` and use the `InteractsWithMedia` trait:
|
||||
|
||||
```php
|
||||
use Spatie\MediaLibrary\HasMedia;
|
||||
use Spatie\MediaLibrary\InteractsWithMedia;
|
||||
|
||||
class BlogPost extends Model implements HasMedia
|
||||
{
|
||||
use InteractsWithMedia;
|
||||
}
|
||||
```
|
||||
|
||||
### Adding Media
|
||||
|
||||
```php
|
||||
$blogPost->addMedia($file)->toMediaCollection('images');
|
||||
$blogPost->addMediaFromUrl($url)->toMediaCollection('images');
|
||||
$blogPost->addMediaFromRequest('file')->toMediaCollection('images');
|
||||
```
|
||||
|
||||
### Defining Collections
|
||||
|
||||
```php
|
||||
public function registerMediaCollections(): void
|
||||
{
|
||||
$this->addMediaCollection('avatar')->singleFile();
|
||||
$this->addMediaCollection('downloads')->useDisk('s3');
|
||||
}
|
||||
```
|
||||
|
||||
### Defining Conversions
|
||||
|
||||
```php
|
||||
use Spatie\MediaLibrary\MediaCollections\Models\Media;
|
||||
use Spatie\Image\Enums\Fit;
|
||||
|
||||
public function registerMediaConversions(?Media $media = null): void
|
||||
{
|
||||
$this->addMediaConversion('thumb')
|
||||
->fit(Fit::Contain, 300, 300)
|
||||
->nonQueued();
|
||||
}
|
||||
```
|
||||
|
||||
### Retrieving Media
|
||||
|
||||
```php
|
||||
$url = $model->getFirstMediaUrl('images');
|
||||
$thumbUrl = $model->getFirstMediaUrl('images', 'thumb');
|
||||
$allMedia = $model->getMedia('images');
|
||||
```
|
||||
|
||||
## Do and Don't
|
||||
|
||||
Do:
|
||||
- Always implement the `HasMedia` interface alongside the `InteractsWithMedia` trait.
|
||||
- Use `?Media $media = null` as the parameter for `registerMediaConversions()`.
|
||||
- Call `->toMediaCollection()` to finalize adding media.
|
||||
- Use `->nonQueued()` for conversions that should run synchronously.
|
||||
- Use `->singleFile()` on collections that should only hold one file.
|
||||
- Use `Spatie\Image\Enums\Fit` enum values for fit methods.
|
||||
|
||||
Don't:
|
||||
- Don't forget to run `php artisan vendor:publish --provider="Spatie\MediaLibrary\MediaLibraryServiceProvider" --tag="medialibrary-migrations"` before migrating.
|
||||
- Don't use `env()` for disk configuration; use `config()` or set it in `config/media-library.php`.
|
||||
- Don't call `addMedia()` without calling `toMediaCollection()` — the media won't be saved.
|
||||
- Don't reference conversion names that aren't registered in `registerMediaConversions()`.
|
||||
|
||||
## References
|
||||
|
||||
- `references/medialibrary-guide.md`
|
||||
|
|
@ -1,577 +0,0 @@
|
|||
# Laravel Media Library Reference
|
||||
|
||||
Complete reference for `spatie/laravel-medialibrary`. Full documentation: https://spatie.be/docs/laravel-medialibrary
|
||||
|
||||
## Model Setup
|
||||
|
||||
Implement `HasMedia` and use `InteractsWithMedia`:
|
||||
|
||||
```php
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Spatie\MediaLibrary\HasMedia;
|
||||
use Spatie\MediaLibrary\InteractsWithMedia;
|
||||
|
||||
class BlogPost extends Model implements HasMedia
|
||||
{
|
||||
use InteractsWithMedia;
|
||||
|
||||
public function registerMediaCollections(): void
|
||||
{
|
||||
$this->addMediaCollection('images');
|
||||
}
|
||||
|
||||
public function registerMediaConversions(?Media $media = null): void
|
||||
{
|
||||
$this->addMediaConversion('thumb')
|
||||
->fit(Fit::Contain, 300, 300);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Adding Media
|
||||
|
||||
### From uploaded file
|
||||
|
||||
```php
|
||||
$model->addMedia($request->file('image'))->toMediaCollection('images');
|
||||
```
|
||||
|
||||
### From request (shorthand)
|
||||
|
||||
```php
|
||||
$model->addMediaFromRequest('image')->toMediaCollection('images');
|
||||
```
|
||||
|
||||
### From URL
|
||||
|
||||
```php
|
||||
$model->addMediaFromUrl('https://example.com/image.jpg')->toMediaCollection('images');
|
||||
```
|
||||
|
||||
### From string content
|
||||
|
||||
```php
|
||||
$model->addMediaFromString('raw content')->usingFileName('file.txt')->toMediaCollection('files');
|
||||
```
|
||||
|
||||
### From base64
|
||||
|
||||
```php
|
||||
$model->addMediaFromBase64($base64Data)->usingFileName('photo.jpg')->toMediaCollection('images');
|
||||
```
|
||||
|
||||
### From stream
|
||||
|
||||
```php
|
||||
$model->addMediaFromStream($stream)->usingFileName('file.pdf')->toMediaCollection('files');
|
||||
```
|
||||
|
||||
### From existing disk
|
||||
|
||||
```php
|
||||
$model->addMediaFromDisk('path/to/file.jpg', 's3')->toMediaCollection('images');
|
||||
```
|
||||
|
||||
### Multiple files from request
|
||||
|
||||
```php
|
||||
$model->addMultipleMediaFromRequest(['images'])->each(function ($fileAdder) {
|
||||
$fileAdder->toMediaCollection('images');
|
||||
});
|
||||
|
||||
$model->addAllMediaFromRequest()->each(function ($fileAdder) {
|
||||
$fileAdder->toMediaCollection('images');
|
||||
});
|
||||
```
|
||||
|
||||
### Copy instead of move
|
||||
|
||||
```php
|
||||
$model->copyMedia($pathToFile)->toMediaCollection('images');
|
||||
// or
|
||||
$model->addMedia($pathToFile)->preservingOriginal()->toMediaCollection('images');
|
||||
```
|
||||
|
||||
## FileAdder Options
|
||||
|
||||
All methods are chainable before calling `toMediaCollection()`:
|
||||
|
||||
```php
|
||||
$model->addMedia($file)
|
||||
->usingName('Custom Name') // display name
|
||||
->usingFileName('custom-name.jpg') // filename on disk
|
||||
->setOrder(3) // order within collection
|
||||
->withCustomProperties(['alt' => 'A landscape photo'])
|
||||
->withManipulations(['thumb' => ['filter' => 'greyscale']])
|
||||
->withResponsiveImages() // generate responsive variants
|
||||
->storingConversionsOnDisk('s3') // put conversions on different disk
|
||||
->addCustomHeaders(['CacheControl' => 'max-age=31536000'])
|
||||
->toMediaCollection('images');
|
||||
```
|
||||
|
||||
### Store on cloud disk
|
||||
|
||||
```php
|
||||
$model->addMedia($file)->toMediaCollectionOnCloudDisk('images');
|
||||
```
|
||||
|
||||
## Media Collections
|
||||
|
||||
Define in `registerMediaCollections()`:
|
||||
|
||||
```php
|
||||
public function registerMediaCollections(): void
|
||||
{
|
||||
// Basic collection
|
||||
$this->addMediaCollection('images');
|
||||
|
||||
// Single file (replacing previous on new upload)
|
||||
$this->addMediaCollection('avatar')
|
||||
->singleFile();
|
||||
|
||||
// Keep only latest N items
|
||||
$this->addMediaCollection('recent_photos')
|
||||
->onlyKeepLatest(5);
|
||||
|
||||
// Specific disk
|
||||
$this->addMediaCollection('downloads')
|
||||
->useDisk('s3');
|
||||
|
||||
// With conversions disk
|
||||
$this->addMediaCollection('photos')
|
||||
->useDisk('s3')
|
||||
->storeConversionsOnDisk('s3-thumbnails');
|
||||
|
||||
// MIME type restriction
|
||||
$this->addMediaCollection('documents')
|
||||
->acceptsMimeTypes(['application/pdf', 'application/zip']);
|
||||
|
||||
// Custom validation
|
||||
$this->addMediaCollection('images')
|
||||
->acceptsFile(function ($file) {
|
||||
return $file->mimeType === 'image/jpeg';
|
||||
});
|
||||
|
||||
// Fallback URL/path when collection is empty
|
||||
$this->addMediaCollection('avatar')
|
||||
->singleFile()
|
||||
->useFallbackUrl('/images/default-avatar.jpg')
|
||||
->useFallbackPath(public_path('/images/default-avatar.jpg'));
|
||||
|
||||
// Enable responsive images for entire collection
|
||||
$this->addMediaCollection('hero_images')
|
||||
->withResponsiveImages();
|
||||
|
||||
// Collection-specific conversions
|
||||
$this->addMediaCollection('photos')
|
||||
->registerMediaConversions(function () {
|
||||
$this->addMediaConversion('card')
|
||||
->fit(Fit::Crop, 400, 400);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## Media Conversions
|
||||
|
||||
Define in `registerMediaConversions()`:
|
||||
|
||||
```php
|
||||
use Spatie\MediaLibrary\MediaCollections\Models\Media;
|
||||
use Spatie\Image\Enums\Fit;
|
||||
|
||||
public function registerMediaConversions(?Media $media = null): void
|
||||
{
|
||||
$this->addMediaConversion('thumb')
|
||||
->fit(Fit::Contain, 300, 300)
|
||||
->nonQueued();
|
||||
|
||||
$this->addMediaConversion('preview')
|
||||
->fit(Fit::Crop, 500, 500)
|
||||
->withResponsiveImages()
|
||||
->queued();
|
||||
|
||||
$this->addMediaConversion('banner')
|
||||
->fit(Fit::Max, 1200, 630)
|
||||
->performOnCollections('images', 'headers')
|
||||
->nonQueued()
|
||||
->sharpen(10);
|
||||
|
||||
// Conditional conversion based on media properties
|
||||
if ($media?->mime_type === 'image/png') {
|
||||
$this->addMediaConversion('png-thumb')
|
||||
->fit(Fit::Contain, 150, 150);
|
||||
}
|
||||
|
||||
// Keep original format instead of converting to jpg
|
||||
$this->addMediaConversion('web')
|
||||
->fit(Fit::Max, 800, 800)
|
||||
->keepOriginalImageFormat();
|
||||
|
||||
// PDF page rendering
|
||||
$this->addMediaConversion('pdf-preview')
|
||||
->pdfPageNumber(1)
|
||||
->fit(Fit::Contain, 400, 400);
|
||||
|
||||
// Video frame extraction
|
||||
$this->addMediaConversion('video-thumb')
|
||||
->extractVideoFrameAtSecond(5)
|
||||
->fit(Fit::Crop, 300, 300);
|
||||
}
|
||||
```
|
||||
|
||||
### Image Manipulation Methods (via spatie/image)
|
||||
|
||||
Resizing and fitting:
|
||||
- `width(int)`, `height(int)` — constrain dimensions
|
||||
- `fit(Fit, int, int)` — fit within bounds using `Fit::Contain`, `Fit::Max`, `Fit::Fill`, `Fit::Stretch`, `Fit::Crop`
|
||||
- `crop(int, int)` — crop to exact dimensions
|
||||
|
||||
Effects:
|
||||
- `sharpen(int)`, `blur(int)`, `pixelate(int)`
|
||||
- `greyscale()`, `sepia()`
|
||||
- `brightness(int)`, `contrast(int)`, `colorize(int, int, int)`
|
||||
|
||||
Orientation:
|
||||
- `orientation(int)`, `flip(string)`, `rotate(int)`
|
||||
|
||||
Format:
|
||||
- `format(string)` — `'jpg'`, `'png'`, `'webp'`, `'avif'`
|
||||
- `quality(int)` — 1-100
|
||||
|
||||
Other:
|
||||
- `border(int, string, string)`, `watermark(string)`
|
||||
- `optimize()`, `nonOptimized()`
|
||||
|
||||
### Conversion Configuration
|
||||
|
||||
- `performOnCollections('col1', 'col2')` — limit to specific collections
|
||||
- `queued()` / `nonQueued()` — run async or sync
|
||||
- `withResponsiveImages()` — also generate responsive variants for this conversion
|
||||
- `keepOriginalImageFormat()` — preserve png/webp/gif instead of converting to jpg
|
||||
- `pdfPageNumber(int)` — which PDF page to render
|
||||
- `extractVideoFrameAtSecond(int)` — video thumbnail timing
|
||||
|
||||
## Retrieving Media
|
||||
|
||||
### Getting media items
|
||||
|
||||
```php
|
||||
$media = $model->getMedia('images'); // all in collection
|
||||
$first = $model->getFirstMedia('images'); // first item
|
||||
$last = $model->getLastMedia('images'); // last item
|
||||
$has = $model->hasMedia('images'); // boolean check
|
||||
```
|
||||
|
||||
### Getting URLs
|
||||
|
||||
```php
|
||||
$url = $model->getFirstMediaUrl('images'); // original URL
|
||||
$thumbUrl = $model->getFirstMediaUrl('images', 'thumb'); // conversion URL
|
||||
$lastUrl = $model->getLastMediaUrl('images', 'thumb');
|
||||
```
|
||||
|
||||
### Getting paths
|
||||
|
||||
```php
|
||||
$path = $model->getFirstMediaPath('images');
|
||||
$thumbPath = $model->getFirstMediaPath('images', 'thumb');
|
||||
```
|
||||
|
||||
### Temporary URLs (S3)
|
||||
|
||||
```php
|
||||
$tempUrl = $model->getFirstTemporaryUrl(
|
||||
now()->addMinutes(30),
|
||||
'images',
|
||||
'thumb'
|
||||
);
|
||||
```
|
||||
|
||||
### Fallback URLs
|
||||
|
||||
```php
|
||||
$url = $model->getFallbackMediaUrl('avatar');
|
||||
```
|
||||
|
||||
### From the Media model
|
||||
|
||||
```php
|
||||
$media = $model->getFirstMedia('images');
|
||||
|
||||
$media->getUrl(); // original URL
|
||||
$media->getUrl('thumb'); // conversion URL
|
||||
$media->getPath(); // disk path
|
||||
$media->getFullUrl(); // full URL with domain
|
||||
$media->getTemporaryUrl(now()->addMinutes(30));
|
||||
$media->hasGeneratedConversion('thumb'); // check if conversion exists
|
||||
```
|
||||
|
||||
### Filtering media
|
||||
|
||||
```php
|
||||
$media = $model->getMedia('images', function (Media $media) {
|
||||
return $media->getCustomProperty('featured') === true;
|
||||
});
|
||||
|
||||
$media = $model->getMedia('images', ['mime_type' => 'image/jpeg']);
|
||||
```
|
||||
|
||||
## Custom Properties
|
||||
|
||||
Store arbitrary metadata on media items:
|
||||
|
||||
```php
|
||||
// When adding
|
||||
$model->addMedia($file)
|
||||
->withCustomProperties([
|
||||
'alt' => 'Descriptive text',
|
||||
'credits' => 'Photographer Name',
|
||||
])
|
||||
->toMediaCollection('images');
|
||||
|
||||
// Get/set on existing media
|
||||
$media->setCustomProperty('alt', 'Updated text');
|
||||
$media->save();
|
||||
|
||||
$alt = $media->getCustomProperty('alt');
|
||||
$has = $media->hasCustomProperty('alt');
|
||||
$media->forgetCustomProperty('alt');
|
||||
$media->save();
|
||||
```
|
||||
|
||||
## Responsive Images
|
||||
|
||||
Generate multiple sizes for optimal loading:
|
||||
|
||||
```php
|
||||
// On the FileAdder
|
||||
$model->addMedia($file)
|
||||
->withResponsiveImages()
|
||||
->toMediaCollection('images');
|
||||
|
||||
// On a conversion
|
||||
$this->addMediaConversion('hero')
|
||||
->fit(Fit::Max, 1200, 800)
|
||||
->withResponsiveImages();
|
||||
|
||||
// On a collection
|
||||
$this->addMediaCollection('photos')
|
||||
->withResponsiveImages();
|
||||
```
|
||||
|
||||
### Using in Blade
|
||||
|
||||
```blade
|
||||
{{-- Renders img tag with srcset --}}
|
||||
{{ $media->toHtml() }}
|
||||
|
||||
{{-- With attributes --}}
|
||||
{{ $media->img()->attributes(['class' => 'w-full', 'alt' => 'Photo']) }}
|
||||
|
||||
{{-- Get srcset string --}}
|
||||
<img src="{{ $media->getUrl() }}" srcset="{{ $media->getSrcset() }}" />
|
||||
|
||||
{{-- Responsive conversion --}}
|
||||
<img src="{{ $media->getUrl('hero') }}" srcset="{{ $media->getSrcset('hero') }}" />
|
||||
```
|
||||
|
||||
### Placeholder SVG
|
||||
|
||||
```php
|
||||
$svg = $media->responsiveImages()->getPlaceholderSvg(); // tiny blurred base64 placeholder
|
||||
```
|
||||
|
||||
## Managing Media
|
||||
|
||||
### Clear a collection
|
||||
|
||||
```php
|
||||
$model->clearMediaCollection('images');
|
||||
```
|
||||
|
||||
### Clear except specific items
|
||||
|
||||
```php
|
||||
$model->clearMediaCollectionExcept('images', $mediaToKeep);
|
||||
```
|
||||
|
||||
### Delete specific media
|
||||
|
||||
```php
|
||||
$model->deleteMedia($mediaId);
|
||||
```
|
||||
|
||||
### Delete all media
|
||||
|
||||
```php
|
||||
$model->deleteAllMedia();
|
||||
```
|
||||
|
||||
### Delete model but keep media files
|
||||
|
||||
```php
|
||||
$model->deletePreservingMedia();
|
||||
```
|
||||
|
||||
### Reorder media
|
||||
|
||||
```php
|
||||
Media::setNewOrder([3, 1, 2]); // media IDs in desired order
|
||||
```
|
||||
|
||||
### Move/copy media between models
|
||||
|
||||
```php
|
||||
$media->move($otherModel, 'images');
|
||||
$media->copy($otherModel, 'images');
|
||||
```
|
||||
|
||||
## Events
|
||||
|
||||
```php
|
||||
use Spatie\MediaLibrary\MediaCollections\Events\MediaHasBeenAddedEvent;
|
||||
use Spatie\MediaLibrary\Conversions\Events\ConversionWillStartEvent;
|
||||
use Spatie\MediaLibrary\Conversions\Events\ConversionHasBeenCompletedEvent;
|
||||
use Spatie\MediaLibrary\MediaCollections\Events\CollectionHasBeenClearedEvent;
|
||||
```
|
||||
|
||||
Listen to these events to hook into the media lifecycle:
|
||||
```php
|
||||
Event::listen(MediaHasBeenAddedEvent::class, function ($event) {
|
||||
$event->media; // the added Media model
|
||||
});
|
||||
|
||||
Event::listen(ConversionHasBeenCompletedEvent::class, function ($event) {
|
||||
$event->media;
|
||||
$event->conversion;
|
||||
});
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
Key `config/media-library.php` options:
|
||||
|
||||
```php
|
||||
return [
|
||||
'disk_name' => 'public', // default disk
|
||||
'max_file_size' => 1024 * 1024 * 10, // 10MB
|
||||
'queue_connection_name' => '', // queue connection
|
||||
'queue_name' => '', // queue name
|
||||
'queue_conversions_by_default' => true, // queue conversions
|
||||
'media_model' => Spatie\MediaLibrary\MediaCollections\Models\Media::class,
|
||||
'file_namer' => Spatie\MediaLibrary\Support\FileNamer\DefaultFileNamer::class,
|
||||
'path_generator' => Spatie\MediaLibrary\Support\PathGenerator\DefaultPathGenerator::class,
|
||||
'url_generator' => Spatie\MediaLibrary\Support\UrlGenerator\DefaultUrlGenerator::class,
|
||||
'image_driver' => 'gd', // 'gd', 'imagick', or 'vips'
|
||||
'image_optimizers' => [/* optimizer config */],
|
||||
'version_urls' => true, // cache busting
|
||||
'default_loading_attribute_value' => null, // 'lazy' for lazy loading
|
||||
];
|
||||
```
|
||||
|
||||
### Custom Path Generator
|
||||
|
||||
```php
|
||||
use Spatie\MediaLibrary\Support\PathGenerator\PathGenerator;
|
||||
|
||||
class CustomPathGenerator implements PathGenerator
|
||||
{
|
||||
public function getPath(Media $media): string
|
||||
{
|
||||
return md5($media->id) . '/';
|
||||
}
|
||||
|
||||
public function getPathForConversions(Media $media): string
|
||||
{
|
||||
return $this->getPath($media) . 'conversions/';
|
||||
}
|
||||
|
||||
public function getPathForResponsiveImages(Media $media): string
|
||||
{
|
||||
return $this->getPath($media) . 'responsive/';
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Custom File Namer
|
||||
|
||||
```php
|
||||
use Spatie\MediaLibrary\Support\FileNamer\FileNamer;
|
||||
|
||||
class CustomFileNamer extends FileNamer
|
||||
{
|
||||
public function originalFileName(string $fileName): string
|
||||
{
|
||||
return Str::slug(pathinfo($fileName, PATHINFO_FILENAME));
|
||||
}
|
||||
|
||||
public function conversionFileName(string $fileName, Conversion $conversion): string
|
||||
{
|
||||
return $this->originalFileName($fileName) . '-' . $conversion->getName();
|
||||
}
|
||||
|
||||
public function responsiveFileName(string $fileName): string
|
||||
{
|
||||
return pathinfo($fileName, PATHINFO_FILENAME);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Custom Media Model
|
||||
|
||||
```php
|
||||
use Spatie\MediaLibrary\MediaCollections\Models\Media as BaseMedia;
|
||||
|
||||
class Media extends BaseMedia
|
||||
{
|
||||
// Add custom methods, scopes, or override behavior
|
||||
}
|
||||
```
|
||||
|
||||
Register in config: `'media_model' => App\Models\Media::class`
|
||||
|
||||
## Downloading Media
|
||||
|
||||
### Single file
|
||||
|
||||
```php
|
||||
return $media->toResponse($request); // download
|
||||
return $media->toInlineResponse($request); // display inline
|
||||
return $media->stream(); // stream
|
||||
```
|
||||
|
||||
### ZIP download of collection
|
||||
|
||||
```php
|
||||
use Spatie\MediaLibrary\Support\MediaStream;
|
||||
|
||||
return MediaStream::create('photos.zip')
|
||||
->addMedia($model->getMedia('images'));
|
||||
```
|
||||
|
||||
## Using with API Resources
|
||||
|
||||
```php
|
||||
class PostResource extends JsonResource
|
||||
{
|
||||
public function toArray($request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'title' => $this->title,
|
||||
'image' => $this->getFirstMediaUrl('images'),
|
||||
'thumb' => $this->getFirstMediaUrl('images', 'thumb'),
|
||||
'media' => $this->getMedia('images')->map(function ($media) {
|
||||
return [
|
||||
'id' => $media->id,
|
||||
'url' => $media->getUrl(),
|
||||
'thumb' => $media->getUrl('thumb'),
|
||||
'name' => $media->name,
|
||||
'size' => $media->size,
|
||||
'type' => $media->mime_type,
|
||||
];
|
||||
}),
|
||||
];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
|
@ -1,205 +0,0 @@
|
|||
---
|
||||
name: passport-development
|
||||
description: "Develops OAuth2 API authentication with Laravel Passport. Activates when installing or configuring Passport; setting up OAuth2 grants (authorization code, client credentials, personal access tokens, device authorization); managing OAuth clients; protecting API routes with token authentication; defining or checking token scopes; configuring SPA cookie authentication; handling token lifetimes and refresh tokens; or when the user mentions Passport, OAuth2, API tokens, bearer tokens, or API authentication. Make sure to use this skill whenever the user works with OAuth2, API tokens, or third-party API access, even if they don't explicitly mention Passport."
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
|
||||
# Passport OAuth2 Authentication
|
||||
|
||||
## Documentation First
|
||||
|
||||
**Always use `search-docs` before writing Passport code.** The documentation covers every grant type, configuration option, and edge case in detail. This skill teaches you how to navigate Passport — the docs have the implementation specifics.
|
||||
|
||||
```
|
||||
search-docs(queries: ["Passport installation"], packages: ["laravel/framework@12.x"])
|
||||
```
|
||||
|
||||
The Passport docs live under the `laravel/framework` package — not `laravel/passport`.
|
||||
|
||||
## When to Apply
|
||||
|
||||
Activate this skill when:
|
||||
|
||||
- Installing or configuring Passport
|
||||
- Setting up OAuth2 authorization grants
|
||||
- Creating or managing OAuth clients
|
||||
- Protecting API routes with token authentication
|
||||
- Defining or checking token scopes
|
||||
- Configuring SPA cookie-based authentication
|
||||
- Choosing between Passport and Sanctum
|
||||
|
||||
## Passport vs. Sanctum
|
||||
|
||||
**Passport** is a full OAuth2 server — use it when third-party applications need to consume your API and when you need OAuth2 authorization code grants, client credentials for machine-to-machine auth, or device authorization flow.
|
||||
|
||||
**Sanctum** is simpler — use it when first-party SPAs, third parties, or mobile apps consume the API but you don't need the full OAuth2 grant flows.
|
||||
|
||||
## Installation
|
||||
|
||||
Three steps are always required:
|
||||
|
||||
### 1. Install Passport
|
||||
|
||||
```bash
|
||||
php artisan install:api --passport
|
||||
```
|
||||
|
||||
This publishes migrations, generates encryption keys, and registers routes.
|
||||
|
||||
### 2. Configure the User model
|
||||
|
||||
The User model needs both the `HasApiTokens` trait AND the `OAuthenticatable` interface. Missing the interface is the most common Passport setup mistake — it causes runtime errors that can be confusing to debug.
|
||||
|
||||
```php
|
||||
use Laravel\Passport\Contracts\OAuthenticatable;
|
||||
use Laravel\Passport\HasApiTokens;
|
||||
|
||||
class User extends Authenticatable implements OAuthenticatable
|
||||
{
|
||||
use HasApiTokens;
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Configure the auth guard
|
||||
|
||||
The `api` guard must use the `passport` driver in `config/auth.php`. Using `token` or `sanctum` here silently breaks Passport authentication.
|
||||
|
||||
```php
|
||||
'guards' => [
|
||||
'api' => [
|
||||
'driver' => 'passport',
|
||||
'provider' => 'users',
|
||||
],
|
||||
],
|
||||
```
|
||||
|
||||
## Choosing a Grant Type
|
||||
|
||||
Matching the right grant to the use case is the most important Passport decision. Use `search-docs` for implementation details of any grant.
|
||||
|
||||
| Use Case | Grant Type | Client Flag |
|
||||
|----------|-----------|-------------|
|
||||
| Third-party app accessing user data | Authorization Code | (default) |
|
||||
| Mobile/SPA without client secret | Authorization Code + PKCE | `--public` |
|
||||
| Machine-to-machine, no user context | Client Credentials | `--client` |
|
||||
| User-generated API keys | Personal Access Tokens | `--personal` |
|
||||
| Smart TV, CLI, IoT devices | Device Authorization | `--device` |
|
||||
|
||||
**Legacy grants** (Password, Implicit) are disabled by default and not recommended. They must be explicitly enabled with `Passport::enablePasswordGrant()` or `Passport::enableImplicitGrant()`.
|
||||
|
||||
## Client Management
|
||||
|
||||
Create clients with the appropriate flag for the grant type:
|
||||
|
||||
```bash
|
||||
php artisan passport:client # Authorization code
|
||||
|
||||
php artisan passport:client --public # PKCE (no secret)
|
||||
|
||||
php artisan passport:client --client # Client credentials
|
||||
|
||||
php artisan passport:client --personal # Personal access tokens
|
||||
|
||||
php artisan passport:client --device # Device authorization
|
||||
|
||||
```
|
||||
|
||||
Additional flags: `--name=`, `--redirect_uri=`, `--provider=`.
|
||||
|
||||
Client secrets are hashed by default — the plain-text secret is only shown at creation time and cannot be retrieved later.
|
||||
|
||||
## Protecting Routes
|
||||
|
||||
Apply `auth:api` middleware. Clients send tokens via the `Authorization: Bearer <token>` header.
|
||||
|
||||
```php
|
||||
Route::get('/user', function (Request $request) {
|
||||
return $request->user();
|
||||
})->middleware('auth:api');
|
||||
```
|
||||
|
||||
### Scope Enforcement
|
||||
|
||||
Scope middleware must come alongside `auth:api`:
|
||||
|
||||
- `CheckToken::using('scope1', 'scope2')` — requires ALL listed scopes
|
||||
- `CheckTokenForAnyScope::using('scope1', 'scope2')` — requires ANY listed scope
|
||||
- `EnsureClientIsResourceOwner::using('scope1')` — restricts to client credential tokens
|
||||
|
||||
```php
|
||||
use Laravel\Passport\Http\Middleware\CheckToken;
|
||||
|
||||
Route::get('/orders', function () {
|
||||
// ...
|
||||
})->middleware(['auth:api', CheckToken::using('orders:read')]);
|
||||
```
|
||||
|
||||
### Programmatic scope checking
|
||||
|
||||
```php
|
||||
if ($request->user()->tokenCan('place-orders')) {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
Use `search-docs` for full scope middleware registration and usage patterns.
|
||||
|
||||
## Key Configuration
|
||||
|
||||
Configure in `AppServiceProvider::boot()`. Use `search-docs` for the full list of options.
|
||||
|
||||
```php
|
||||
// Token lifetimes (each is independent)
|
||||
Passport::tokensExpireIn(now()->addDays(15));
|
||||
Passport::refreshTokensExpireIn(now()->addDays(30));
|
||||
Passport::personalAccessTokensExpireIn(now()->addMonths(6));
|
||||
|
||||
// Define scopes
|
||||
Passport::tokensCan([
|
||||
'place-orders' => 'Place orders',
|
||||
'check-status' => 'Check order status',
|
||||
]);
|
||||
```
|
||||
|
||||
## SPA Cookie Authentication
|
||||
|
||||
For first-party SPAs, the `CreateFreshApiToken` middleware issues a `laravel_token` cookie containing an encrypted JWT. The SPA must include CSRF tokens — missing the `X-CSRF-TOKEN` or `X-XSRF-TOKEN` header causes 419 errors.
|
||||
|
||||
Use `search-docs` for setup details — this feature has specific CSRF and cookie configuration requirements.
|
||||
|
||||
## Testing
|
||||
|
||||
Passport provides helpers to bypass full OAuth flows in tests:
|
||||
|
||||
```php
|
||||
Passport::actingAs($user, ['scope1', 'scope2']);
|
||||
Passport::actingAsClient($client, ['scope1']);
|
||||
```
|
||||
|
||||
## Token Maintenance
|
||||
|
||||
```bash
|
||||
php artisan passport:purge # Purge revoked & expired
|
||||
|
||||
php artisan passport:purge --revoked # Only revoked
|
||||
|
||||
php artisan passport:purge --expired # Only expired
|
||||
|
||||
```
|
||||
|
||||
Schedule `passport:purge` for regular expired token clean-up.
|
||||
|
||||
## Events
|
||||
|
||||
All in `Laravel\Passport\Events`: `AccessTokenCreated`, `AccessTokenRevoked`, `RefreshTokenCreated`.
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
- **Missing `OAuthenticatable` interface** — both the `HasApiTokens` trait and the `OAuthenticatable` interface are required on the User model. Missing the interface causes runtime errors.
|
||||
- **Wrong guard driver** — the `api` guard must use `passport`, not `token` or `sanctum`. This fails silently.
|
||||
- **Token lifetime confusion** — access token, refresh token, and personal access token lifetimes are all independent settings.
|
||||
- **Missing CSRF for SPA cookie auth** — `CreateFreshApiToken` requires CSRF tokens. Use `Passport::ignoreCsrfToken()` only if you understand the security implications.
|
||||
- **Client secrets are hashed** — the plain-text secret is only available at creation time.
|
||||
- **Legacy grants are disabled** — Password and Implicit grants must be explicitly enabled and are not recommended.
|
||||
|
|
@ -1,203 +0,0 @@
|
|||
---
|
||||
name: pest-testing
|
||||
description: "Use this skill for Pest PHP testing in Laravel projects only. Trigger whenever any test is being written, edited, fixed, or refactored — including fixing tests that broke after a code change, adding assertions, converting PHPUnit to Pest, adding datasets, and TDD workflows. Always activate when the user asks how to write something in Pest, mentions test files or directories (tests/Feature, tests/Unit, tests/Browser), or needs browser testing, smoke testing multiple pages for JS errors, architecture tests, or faster test runs with Test Impact Analysis. Covers: test()/it()/expect() syntax, datasets, mocking, browser testing (visit/click/fill), smoke testing, arch(), Livewire component tests, RefreshDatabase, Tia (--tia), sharding, and all Pest 5 features. Do not use for factories, seeders, migrations, controllers, models, or non-test PHP code."
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
|
||||
# Pest Testing 5
|
||||
|
||||
## Documentation
|
||||
|
||||
Use `search-docs` for detailed Pest 5 patterns and documentation.
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### Creating Tests
|
||||
|
||||
All tests must be written using Pest. Use `php artisan make:test --pest {name}`.
|
||||
|
||||
The `{name}` argument should include only the path and test name, but should not include the test suite.
|
||||
- Incorrect: `php artisan make:test --pest Feature/SomeFeatureTest` will generate `tests/Feature/Feature/SomeFeatureTest.php`
|
||||
- Correct: `php artisan make:test --pest SomeControllerTest` will generate `tests/Feature/SomeControllerTest.php`
|
||||
- Incorrect: `php artisan make:test --pest --unit Unit/SomeServiceTest` will generate `tests/Unit/Unit/SomeServiceTest.php`
|
||||
- Correct: `php artisan make:test --pest --unit SomeServiceTest` will generate `tests/Unit/SomeServiceTest.php`
|
||||
|
||||
### Test Organization
|
||||
|
||||
- Unit/Feature tests: `tests/Feature` and `tests/Unit` directories.
|
||||
- Browser tests: `tests/Browser/` directory.
|
||||
- Do NOT remove tests without approval - these are core application code.
|
||||
|
||||
### Basic Test Structure
|
||||
|
||||
Pest supports both `test()` and `it()` functions. Before writing new tests, check existing test files in the same directory to match the project's convention. Use `test()` if existing tests use `test()`, or `it()` if they use `it()`.
|
||||
|
||||
<!-- Basic Pest Test Example -->
|
||||
```php
|
||||
it('is true', function () {
|
||||
expect(true)->toBeTrue();
|
||||
});
|
||||
```
|
||||
|
||||
### Running Tests
|
||||
|
||||
- Run minimal tests with filter before finalizing: `php artisan test --compact --filter=testName`.
|
||||
- Run all tests: `php artisan test --compact`.
|
||||
- Run file: `php artisan test --compact tests/Feature/ExampleTest.php`.
|
||||
- Run only tests affected by recent changes (Tia): `./vendor/bin/pest --parallel --tia`.
|
||||
|
||||
## Assertions
|
||||
|
||||
Use specific assertions (`assertSuccessful()`, `assertNotFound()`) instead of `assertStatus()`:
|
||||
|
||||
<!-- Pest Response Assertion -->
|
||||
```php
|
||||
it('returns all', function () {
|
||||
$this->postJson('/api/docs', [])->assertSuccessful();
|
||||
});
|
||||
```
|
||||
|
||||
| Use | Instead of |
|
||||
|-----|------------|
|
||||
| `assertSuccessful()` | `assertStatus(200)` |
|
||||
| `assertNotFound()` | `assertStatus(404)` |
|
||||
| `assertForbidden()` | `assertStatus(403)` |
|
||||
|
||||
## Mocking
|
||||
|
||||
Import mock function before use: `use function Pest\Laravel\mock;`
|
||||
|
||||
## Datasets
|
||||
|
||||
Use datasets for repetitive tests (validation rules, etc.):
|
||||
|
||||
<!-- Pest Dataset Example -->
|
||||
```php
|
||||
it('has emails', function (string $email) {
|
||||
expect($email)->not->toBeEmpty();
|
||||
})->with([
|
||||
'james' => 'james@laravel.com',
|
||||
'taylor' => 'taylor@laravel.com',
|
||||
]);
|
||||
```
|
||||
|
||||
## Pest 5 Features
|
||||
|
||||
| Feature | Purpose |
|
||||
|---------|---------|
|
||||
| Tia (Test Impact Analysis) | Rerun only tests affected by recent changes |
|
||||
| Time-Balanced Sharding | Split tests across CI shards by execution time |
|
||||
| New Validation Expectations | `toBeEmail()`, `toBeUlid()`, `toBeIpAddress()`, and more |
|
||||
| Browser Testing | Full integration tests in real browsers |
|
||||
| Smoke Testing | Validate multiple pages quickly |
|
||||
| Visual Regression | Compare screenshots for visual changes |
|
||||
| Architecture Testing | Enforce code conventions |
|
||||
|
||||
### Tia (Test Impact Analysis)
|
||||
|
||||
Tia reruns only tests affected by recent changes and replays cached results for the rest, dramatically reducing suite duration:
|
||||
|
||||
<!-- Tia Example -->
|
||||
```shell
|
||||
./vendor/bin/pest --parallel --tia
|
||||
```
|
||||
|
||||
- Replayed tests are not skipped — cached tests store everything they produced, including covered lines and branches.
|
||||
- Detects Laravel, Symfony, Livewire, and Inertia automatically.
|
||||
|
||||
### New Validation Expectations
|
||||
|
||||
Pest 5 ships eight new validation matchers, all supporting `.not` negation:
|
||||
|
||||
<!-- Pest 5 Validation Expectations -->
|
||||
```php
|
||||
expect('nuno@pestphp.com')->toBeEmail();
|
||||
expect('01ARZ3NDEKTSV4RRFFQ69G5FAV')->toBeUlid();
|
||||
expect('192.168.1.1')->toBeIpAddress();
|
||||
expect('00:1a:2b:3c:4d:5e')->toBeMacAddress();
|
||||
expect('example.com')->toBeHostname();
|
||||
expect('example.co.uk')->toBeDomain();
|
||||
expect('Zm9vYmFy')->toBeBase64();
|
||||
expect('deadbeef')->toBeHexadecimal();
|
||||
```
|
||||
|
||||
### Time-Balanced Sharding
|
||||
|
||||
Distribute tests across CI shards by execution time rather than count:
|
||||
|
||||
<!-- Pest Sharding Example -->
|
||||
```shell
|
||||
./vendor/bin/pest --update-shards
|
||||
./vendor/bin/pest --shard=1/4
|
||||
```
|
||||
|
||||
Commit `tests/.pest/shards.json` to the repository so CI shards stay consistent.
|
||||
|
||||
### Browser Test Example
|
||||
|
||||
Browser tests run in real browsers for full integration testing:
|
||||
|
||||
- Browser tests live in `tests/Browser/`.
|
||||
- Use Laravel features like `Event::fake()`, `assertAuthenticated()`, and model factories.
|
||||
- Use `RefreshDatabase` for clean state per test.
|
||||
- Interact with page: click, type, scroll, select, submit, drag-and-drop, touch gestures.
|
||||
- Test on multiple browsers (Chrome, Firefox, Safari) if requested.
|
||||
- Test on different devices/viewports (iPhone 14 Pro, tablets) if requested.
|
||||
- Switch color schemes (light/dark mode) when appropriate.
|
||||
- Take screenshots or pause tests for debugging.
|
||||
|
||||
<!-- Pest Browser Test Example -->
|
||||
```php
|
||||
it('may reset the password', function () {
|
||||
Notification::fake();
|
||||
|
||||
$this->actingAs(User::factory()->create());
|
||||
|
||||
$page = visit('/sign-in');
|
||||
|
||||
$page->assertSee('Sign In')
|
||||
->assertNoJavaScriptErrors()
|
||||
->click('Forgot Password?')
|
||||
->fill('email', 'nuno@laravel.com')
|
||||
->click('Send Reset Link')
|
||||
->assertSee('We have emailed your password reset link!');
|
||||
|
||||
Notification::assertSent(ResetPassword::class);
|
||||
});
|
||||
```
|
||||
|
||||
### Smoke Testing
|
||||
|
||||
Quickly validate multiple pages have no JavaScript errors:
|
||||
|
||||
<!-- Pest Smoke Testing Example -->
|
||||
```php
|
||||
$pages = visit(['/', '/about', '/contact']);
|
||||
|
||||
$pages->assertNoJavaScriptErrors()->assertNoConsoleLogs();
|
||||
```
|
||||
|
||||
### Visual Regression Testing
|
||||
|
||||
Capture and compare screenshots to detect visual changes.
|
||||
|
||||
### Architecture Testing
|
||||
|
||||
<!-- Architecture Test Example -->
|
||||
```php
|
||||
arch('controllers')
|
||||
->expect('App\Http\Controllers')
|
||||
->toExtendNothing()
|
||||
->toHaveSuffix('Controller');
|
||||
```
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
- Not importing `use function Pest\Laravel\mock;` before using mock
|
||||
- Using `assertStatus(200)` instead of `assertSuccessful()`
|
||||
- Forgetting datasets for repetitive validation tests
|
||||
- Deleting tests without approval
|
||||
- Forgetting `assertNoJavaScriptErrors()` in browser tests
|
||||
- Prefixing `Feature/` or `Unit/` in `{name}` when using `make:test`
|
||||
|
|
@ -1,80 +0,0 @@
|
|||
---
|
||||
name: socialite-development
|
||||
description: "Manages OAuth social authentication with Laravel Socialite. Activate when adding social login providers; configuring OAuth redirect/callback flows; retrieving authenticated user details; customizing scopes or parameters; setting up community providers; testing with Socialite fakes; or when the user mentions social login, OAuth, Socialite, or third-party authentication."
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
|
||||
# Socialite Authentication
|
||||
|
||||
## Documentation
|
||||
|
||||
Use `search-docs` for detailed Socialite patterns and documentation (installation, configuration, routing, callbacks, testing, scopes, stateless auth).
|
||||
|
||||
## Available Providers
|
||||
|
||||
Built-in: `facebook`, `twitter`, `twitter-oauth-2`, `linkedin`, `linkedin-openid`, `google`, `github`, `gitlab`, `bitbucket`, `slack`, `slack-openid`, `twitch`
|
||||
|
||||
Community: 150+ additional providers at [socialiteproviders.com](https://socialiteproviders.com). For provider-specific setup, use `WebFetch` on `https://socialiteproviders.com/{provider-name}`.
|
||||
|
||||
Configuration key in `config/services.php` must match the driver name exactly — note the hyphenated keys: `twitter-oauth-2`, `linkedin-openid`, `slack-openid`.
|
||||
|
||||
Twitter/X: Use `twitter-oauth-2` (OAuth 2.0) for new projects. The legacy `twitter` driver is OAuth 1.0. Driver names remain unchanged despite the platform rebrand.
|
||||
|
||||
Community providers differ from built-in providers in the following ways:
|
||||
- Installed via `composer require socialiteproviders/{name}`
|
||||
- Must register via event listener — NOT auto-discovered like built-in providers
|
||||
- Use `search-docs` for the registration pattern
|
||||
|
||||
## Adding a Provider
|
||||
|
||||
### 1. Configure the provider
|
||||
|
||||
Add the provider's `client_id`, `client_secret`, and `redirect` to `config/services.php`. The config key must match the driver name exactly.
|
||||
|
||||
### 2. Create redirect and callback routes
|
||||
|
||||
Two routes are needed: one that calls `Socialite::driver('provider')->redirect()` to send the user to the OAuth provider, and one that calls `Socialite::driver('provider')->user()` to receive the callback and retrieve user details.
|
||||
|
||||
### 3. Authenticate and store the user
|
||||
|
||||
In the callback, use `updateOrCreate` to find or create a user record from the provider's response (`id`, `name`, `email`, `token`, `refreshToken`), then call `Auth::login()`.
|
||||
|
||||
### 4. Customize the redirect (optional)
|
||||
|
||||
- `scopes()` — merge additional scopes with the provider's defaults
|
||||
- `setScopes()` — replace all scopes entirely
|
||||
- `with()` — pass optional parameters (e.g., `['hd' => 'example.com']` for Google)
|
||||
- `asBotUser()` — Slack only; generates a bot token (`xoxb-`) instead of a user token (`xoxp-`). Must be called before both `redirect()` and `user()`. Only the `token` property will be hydrated on the user object.
|
||||
- `stateless()` — for API/SPA contexts where session state is not maintained
|
||||
|
||||
### 5. Verify
|
||||
|
||||
1. Config key matches driver name exactly (check the list above for hyphenated names)
|
||||
2. `client_id`, `client_secret`, and `redirect` are all present
|
||||
3. Redirect URL matches what is registered in the provider's OAuth dashboard
|
||||
4. Callback route handles denied grants (when user declines authorization)
|
||||
|
||||
Use `search-docs` for complete code examples of each step.
|
||||
|
||||
## Additional Features
|
||||
|
||||
Use `search-docs` for usage details on: `enablePKCE()`, `userFromToken($token)`, `userFromTokenAndSecret($token, $secret)` (OAuth 1.0), retrieving user details.
|
||||
|
||||
User object: `getId()`, `getName()`, `getEmail()`, `getAvatar()`, `getNickname()`, `token`, `refreshToken`, `expiresIn`, `approvedScopes`
|
||||
|
||||
## Testing
|
||||
|
||||
Socialite provides `Socialite::fake()` for testing redirects and callbacks. Use `search-docs` for faking redirects, callback user data, custom token properties, and assertion methods.
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
- Config key must match driver name exactly — hyphenated drivers need hyphenated keys (`linkedin-openid`, `slack-openid`, `twitter-oauth-2`). Mismatch silently fails.
|
||||
- Every provider needs `client_id`, `client_secret`, and `redirect` in `config/services.php`. Missing any one causes cryptic errors.
|
||||
- `scopes()` merges with defaults; `setScopes()` replaces all scopes entirely.
|
||||
- Missing `stateless()` in API/SPA contexts causes `InvalidStateException`.
|
||||
- Redirect URL in `config/services.php` must exactly match the provider's OAuth dashboard (including trailing slashes and protocol).
|
||||
- Do not pass `state`, `response_type`, `client_id`, `redirect_uri`, or `scope` via `with()` — these are reserved.
|
||||
- Community providers require event listener registration via `SocialiteWasCalled`.
|
||||
- `user()` throws when the user declines authorization. Always handle denied grants.
|
||||
|
|
@ -1,119 +0,0 @@
|
|||
---
|
||||
name: tailwindcss-development
|
||||
description: "Always invoke when the user's message includes 'tailwind' in any form. Also invoke for: building responsive grid layouts (multi-column card grids, product grids), flex/grid page structures (dashboards with sidebars, fixed topbars, mobile-toggle navs), styling UI components (cards, tables, navbars, pricing sections, forms, inputs, badges), adding dark mode variants, fixing spacing or typography, and Tailwind v3/v4 work. The core use case: writing or fixing Tailwind utility classes in HTML templates (Blade, JSX, Vue). Skip for backend PHP logic, database queries, API routes, JavaScript with no HTML/CSS component, CSS file audits, build tool configuration, and vanilla CSS."
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
|
||||
# Tailwind CSS Development
|
||||
|
||||
## Documentation
|
||||
|
||||
Use `search-docs` for detailed Tailwind CSS v4 patterns and documentation.
|
||||
|
||||
## Basic Usage
|
||||
|
||||
- Use Tailwind CSS classes to style HTML. Check and follow existing Tailwind conventions in the project before introducing new patterns.
|
||||
- Offer to extract repeated patterns into components that match the project's conventions (e.g., Blade, JSX, Vue).
|
||||
- Consider class placement, order, priority, and defaults. Remove redundant classes, add classes to parent or child elements carefully to reduce repetition, and group elements logically.
|
||||
|
||||
## Tailwind CSS v4 Specifics
|
||||
|
||||
- Always use Tailwind CSS v4 and avoid deprecated utilities.
|
||||
- `corePlugins` is not supported in Tailwind v4.
|
||||
|
||||
### CSS-First Configuration
|
||||
|
||||
In Tailwind v4, configuration is CSS-first using the `@theme` directive — no separate `tailwind.config.js` file is needed:
|
||||
|
||||
<!-- CSS-First Config -->
|
||||
```css
|
||||
@theme {
|
||||
--color-brand: oklch(0.72 0.11 178);
|
||||
}
|
||||
```
|
||||
|
||||
### Import Syntax
|
||||
|
||||
In Tailwind v4, import Tailwind with a regular CSS `@import` statement instead of the `@tailwind` directives used in v3:
|
||||
|
||||
<!-- v4 Import Syntax -->
|
||||
```diff
|
||||
- @tailwind base;
|
||||
- @tailwind components;
|
||||
- @tailwind utilities;
|
||||
+ @import "tailwindcss";
|
||||
```
|
||||
|
||||
### Replaced Utilities
|
||||
|
||||
Tailwind v4 removed deprecated utilities. Use the replacements shown below. Opacity values remain numeric.
|
||||
|
||||
| Deprecated | Replacement |
|
||||
|------------|-------------|
|
||||
| bg-opacity-* | bg-black/* |
|
||||
| text-opacity-* | text-black/* |
|
||||
| border-opacity-* | border-black/* |
|
||||
| divide-opacity-* | divide-black/* |
|
||||
| ring-opacity-* | ring-black/* |
|
||||
| placeholder-opacity-* | placeholder-black/* |
|
||||
| flex-shrink-* | shrink-* |
|
||||
| flex-grow-* | grow-* |
|
||||
| overflow-ellipsis | text-ellipsis |
|
||||
| decoration-slice | box-decoration-slice |
|
||||
| decoration-clone | box-decoration-clone |
|
||||
|
||||
## Spacing
|
||||
|
||||
Use `gap` utilities instead of margins for spacing between siblings:
|
||||
|
||||
<!-- Gap Utilities -->
|
||||
```html
|
||||
<div class="flex gap-8">
|
||||
<div>Item 1</div>
|
||||
<div>Item 2</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
## Dark Mode
|
||||
|
||||
If existing pages and components support dark mode, new pages and components must support it the same way, typically using the `dark:` variant:
|
||||
|
||||
<!-- Dark Mode -->
|
||||
```html
|
||||
<div class="bg-white dark:bg-gray-900 text-gray-900 dark:text-white">
|
||||
Content adapts to color scheme
|
||||
</div>
|
||||
```
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Flexbox Layout
|
||||
|
||||
<!-- Flexbox Layout -->
|
||||
```html
|
||||
<div class="flex items-center justify-between gap-4">
|
||||
<div>Left content</div>
|
||||
<div>Right content</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
### Grid Layout
|
||||
|
||||
<!-- Grid Layout -->
|
||||
```html
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
<div>Card 1</div>
|
||||
<div>Card 2</div>
|
||||
<div>Card 3</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
- Using deprecated v3 utilities (bg-opacity-*, flex-shrink-*, etc.)
|
||||
- Using `@tailwind` directives instead of `@import "tailwindcss"`
|
||||
- Trying to use `tailwind.config.js` instead of CSS `@theme` directive
|
||||
- Using margins for spacing between siblings instead of gap utilities
|
||||
- Forgetting to add dark mode variants when the project uses dark mode
|
||||
|
|
@ -1,460 +0,0 @@
|
|||
# Laravel 12 to 13 Upgrade Specialist
|
||||
|
||||
You are an expert Laravel upgrade specialist with deep knowledge of both Laravel 12.x and 13.0. Your task is to systematically upgrade the application from Laravel 12 to 13 while ensuring all functionality remains intact. You understand the nuances of breaking changes and can identify affected code patterns with precision.
|
||||
|
||||
## Core Principle: Documentation-First Approach
|
||||
|
||||
**IMPORTANT:** Always use the `search-docs` tool whenever you need:
|
||||
|
||||
- Specific code examples for implementing Laravel 13 features
|
||||
- Clarification on breaking changes or new behavior
|
||||
- Verification of upgrade patterns before applying them
|
||||
- Examples of correct usage for renamed classes or methods
|
||||
|
||||
The official Laravel documentation is your primary source of truth. Consult it before making assumptions or implementing changes.
|
||||
|
||||
## Upgrade Process
|
||||
|
||||
Follow this systematic process to upgrade the application:
|
||||
|
||||
### 1. Assess Current State
|
||||
|
||||
Before making any changes:
|
||||
|
||||
- Check `composer.json` for the current Laravel version constraint
|
||||
- Run `{{ $assist->composerCommand('show laravel/framework') }}` to confirm installed version
|
||||
- Identify middleware references to `VerifyCsrfToken` or `ValidateCsrfToken`
|
||||
- Review `config/cache.php` for serialization settings
|
||||
- Review `config/session.php` for cookie name configuration
|
||||
|
||||
### 2. Create Safety Net
|
||||
|
||||
- Ensure you're working on a dedicated branch
|
||||
- Run the existing test suite to establish baseline
|
||||
- Note any custom cache store implementations or queue driver implementations
|
||||
|
||||
### 3. Analyze Codebase for Breaking Changes
|
||||
|
||||
Search the codebase for patterns affected by v13 changes:
|
||||
|
||||
**High Priority Searches:**
|
||||
|
||||
- `VerifyCsrfToken` or `ValidateCsrfToken` — Must rename to `PreventRequestForgery`
|
||||
- `composer.json` — Dependency version constraints to update
|
||||
- `phpunit.xml` or `pest` config — Test framework version compatibility
|
||||
|
||||
**Medium Priority Searches:**
|
||||
|
||||
- `config/cache.php` — Check for `serializable_classes` configuration
|
||||
- Code that stores PHP objects in cache — May need explicit class allow-lists
|
||||
|
||||
**Low Priority Searches:**
|
||||
|
||||
- `$event->exceptionOccurred` — Renamed to `$event->exception` in `JobAttempted`
|
||||
- `$event->connection` on `QueueBusy` — Renamed to `$connectionName`
|
||||
- `pagination::default` or `pagination::simple-default` — View names changed
|
||||
- `Container::call` with nullable class defaults — Behavior changed
|
||||
- Manager `extend` callbacks using `$this` — Binding changed
|
||||
- Custom `Str` factories in tests — Now reset between tests
|
||||
|
||||
### 4. Apply Changes Systematically
|
||||
|
||||
For each category of changes:
|
||||
|
||||
1. **Search** for affected patterns using grep/search tools
|
||||
2. **Consult documentation** — Use `search-docs` tool to verify correct upgrade patterns and examples
|
||||
3. **List** all files that need modification
|
||||
4. **Apply** the fix consistently across all occurrences
|
||||
5. **Verify** each change doesn't break functionality
|
||||
|
||||
### 5. Update Dependencies
|
||||
|
||||
After code changes are complete:
|
||||
|
||||
```bash
|
||||
{{ $assist->composerCommand('require laravel/framework:^13.0 --with-all-dependencies') }}
|
||||
```
|
||||
|
||||
### 6. Test and Verify
|
||||
|
||||
- Run the full test suite
|
||||
- Verify CSRF protection still works correctly
|
||||
- Check cache read/write operations
|
||||
- Test any queue listeners that reference event properties
|
||||
|
||||
## Execution Strategy
|
||||
|
||||
When upgrading, maximize efficiency by:
|
||||
|
||||
- **Batch similar changes** — Group all CSRF middleware renames, then all config updates, etc.
|
||||
- **Use parallel agents** for independent file modifications
|
||||
- **Prioritize high-impact changes** that could cause immediate failures
|
||||
- **Test incrementally** — Verify after each category of changes
|
||||
|
||||
# Upgrading from Laravel 12.x to 13.0
|
||||
|
||||
> [!NOTE]
|
||||
> We attempt to document every possible breaking change. Since some of these breaking changes are in obscure parts of the framework only a portion of these changes may actually affect your application.
|
||||
|
||||
## Updating Dependencies
|
||||
|
||||
**Likelihood Of Impact: High**
|
||||
|
||||
Update the following dependencies in your application's `composer.json` file:
|
||||
|
||||
@boostsnippet('Dependency Updates', 'json')
|
||||
{
|
||||
"require": {
|
||||
"laravel/framework": "^13.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"laravel/tinker": "^3.0",
|
||||
"phpunit/phpunit": "^12.0",
|
||||
"pestphp/pest": "^4.0"
|
||||
}
|
||||
}
|
||||
@endboostsnippet
|
||||
|
||||
Run the update:
|
||||
|
||||
```bash
|
||||
{{ $assist->composerCommand('update') }}
|
||||
```
|
||||
|
||||
## Updating the Laravel Installer
|
||||
|
||||
If you use the Laravel installer CLI tool, update it for Laravel 13.x compatibility:
|
||||
|
||||
@if($usesHerd)
|
||||
|
||||
```bash
|
||||
herd laravel:update
|
||||
```
|
||||
|
||||
@else
|
||||
|
||||
```bash
|
||||
{{ $assist->composerCommand('global update laravel/installer') }}
|
||||
```
|
||||
|
||||
@endif
|
||||
|
||||
## Cache
|
||||
|
||||
### Cache Prefixes and Session Cookie Names
|
||||
|
||||
**Likelihood Of Impact: Low**
|
||||
|
||||
Laravel's default cache and Redis key prefixes now use hyphenated suffixes. In addition, the default session cookie name now uses `Str::snake(...)` for the application name.
|
||||
|
||||
In most applications, this change will not apply because application-level configuration files already define these values. This primarily affects applications that rely on framework-level fallback configuration when corresponding application config values are not present.
|
||||
|
||||
If your application relies on these generated defaults, cache keys and session cookie names may change after upgrading:
|
||||
|
||||
@boostsnippet('Cache Prefix Changes', 'php')
|
||||
// Laravel <= 12.x
|
||||
Str::slug((string) env('APP*NAME', 'laravel'), '*').'_cache_';
|
||||
Str::slug((string) env('APP*NAME', 'laravel'), '*').'_database_';
|
||||
Str::slug((string) env('APP*NAME', 'laravel'), '*').'\_session';
|
||||
|
||||
// Laravel >= 13.x
|
||||
Str::slug((string) env('APP_NAME', 'laravel')).'-cache-';
|
||||
Str::slug((string) env('APP_NAME', 'laravel')).'-database-';
|
||||
Str::snake((string) env('APP_NAME', 'laravel')).'\_session';
|
||||
@endboostsnippet
|
||||
|
||||
To retain previous behavior, explicitly configure `CACHE_PREFIX`, `REDIS_PREFIX`, and `SESSION_COOKIE` in your environment.
|
||||
|
||||
### `Store` and `Repository` Contracts: `touch`
|
||||
|
||||
**Likelihood Of Impact: Very Low**
|
||||
|
||||
The cache contracts now include a `touch` method for extending item TTLs. If you maintain custom cache store implementations, you should add this method:
|
||||
|
||||
@boostsnippet('Cache Store Touch', 'php')
|
||||
// Illuminate\Contracts\Cache\Store
|
||||
public function touch($key, $seconds);
|
||||
@endboostsnippet
|
||||
|
||||
### Cache `serializable_classes` Configuration
|
||||
|
||||
**Likelihood Of Impact: Medium**
|
||||
|
||||
The default application `cache` configuration now includes a `serializable_classes` option set to `false`. This hardens cache unserialization behavior to help prevent PHP deserialization gadget chain attacks if your application's `APP_KEY` is leaked. If your application intentionally stores PHP objects in cache, you should explicitly list the classes that may be unserialized:
|
||||
|
||||
@boostsnippet('Cache Serializable Classes', 'php')
|
||||
'serializable_classes' => [
|
||||
App\Data\CachedDashboardStats::class,
|
||||
App\Support\CachedPricingSnapshot::class,
|
||||
],
|
||||
@endboostsnippet
|
||||
|
||||
If your application previously relied on unserializing arbitrary cached objects, you will need to migrate that usage to explicit class allow-lists or to non-object cache payloads (such as arrays).
|
||||
|
||||
## Container
|
||||
|
||||
### `Container::call` and Nullable Class Defaults
|
||||
|
||||
**Likelihood Of Impact: Low**
|
||||
|
||||
`Container::call` now respects nullable class parameter defaults when no binding exists, matching constructor injection behavior introduced in Laravel 12:
|
||||
|
||||
@boostsnippet('Container Call Nullable', 'php')
|
||||
$container->call(function (?Carbon $date = null) {
|
||||
return $date;
|
||||
});
|
||||
|
||||
// Laravel <= 12.x: Carbon instance
|
||||
// Laravel >= 13.x: null
|
||||
@endboostsnippet
|
||||
|
||||
If your method-call injection logic depended on the previous behavior, you may need to update it.
|
||||
|
||||
## Contracts
|
||||
|
||||
### `Dispatcher` Contract: `dispatchAfterResponse`
|
||||
|
||||
**Likelihood Of Impact: Very Low**
|
||||
|
||||
The `Illuminate\Contracts\Bus\Dispatcher` contract now includes the `dispatchAfterResponse($command, $handler = null)` method.
|
||||
|
||||
If you maintain a custom dispatcher implementation, add this method to your class.
|
||||
|
||||
### `ResponseFactory` Contract: `eventStream`
|
||||
|
||||
**Likelihood Of Impact: Very Low**
|
||||
|
||||
The `Illuminate\Contracts\Routing\ResponseFactory` contract now includes an `eventStream` signature.
|
||||
|
||||
If you maintain a custom implementation of this contract, you should add this method.
|
||||
|
||||
### `MustVerifyEmail` Contract: `markEmailAsUnverified`
|
||||
|
||||
**Likelihood Of Impact: Very Low**
|
||||
|
||||
The `Illuminate\Contracts\Auth\MustVerifyEmail` contract now includes `markEmailAsUnverified()`.
|
||||
|
||||
If you provide a custom implementation of this contract, add this method to remain compatible.
|
||||
|
||||
## Database
|
||||
|
||||
### MySQL `DELETE` Queries With `JOIN`, `ORDER BY`, and `LIMIT`
|
||||
|
||||
**Likelihood Of Impact: Low**
|
||||
|
||||
Laravel now compiles full `DELETE ... JOIN` queries including `ORDER BY` and `LIMIT` for MySQL grammar.
|
||||
|
||||
In previous versions, `ORDER BY` / `LIMIT` clauses could be silently ignored on joined deletes. In Laravel 13, these clauses are included in the generated SQL. As a result, database engines that do not support this syntax (such as standard MySQL / MariaDB variants) may now throw a `QueryException` instead of executing an unbounded delete.
|
||||
|
||||
## Eloquent
|
||||
|
||||
### Model Booting and Nested Instantiation
|
||||
|
||||
**Likelihood Of Impact: Very Low**
|
||||
|
||||
Creating a new model instance while that model is still booting is now disallowed and throws a `LogicException`.
|
||||
|
||||
This affects code that instantiates models from inside model `boot` methods or trait `boot*` methods:
|
||||
|
||||
@boostsnippet('Model Booting', 'php')
|
||||
protected static function boot()
|
||||
{
|
||||
parent::boot();
|
||||
|
||||
// No longer allowed during booting...
|
||||
(new static())->getTable();
|
||||
|
||||
}
|
||||
@endboostsnippet
|
||||
|
||||
Move this logic outside the boot cycle to avoid nested booting.
|
||||
|
||||
### Polymorphic Pivot Table Name Generation
|
||||
|
||||
**Likelihood Of Impact: Low**
|
||||
|
||||
When table names are inferred for polymorphic pivot models using custom pivot model classes, Laravel now generates pluralized names.
|
||||
|
||||
If your application depended on the previous singular inferred names for morph pivot tables and used custom pivot classes, you should explicitly define the table name on your pivot model.
|
||||
|
||||
### Collection Model Serialization Restores Eager-Loaded Relations
|
||||
|
||||
**Likelihood Of Impact: Low**
|
||||
|
||||
When Eloquent model collections are serialized and restored (such as in queued jobs), eager-loaded relations are now restored for the collection's models.
|
||||
|
||||
If your code depended on relations not being present after deserialization, you may need to adjust that logic.
|
||||
|
||||
## HTTP Client
|
||||
|
||||
### HTTP Client `Response::throw` and `throwIf` Signatures
|
||||
|
||||
**Likelihood Of Impact: Very Low**
|
||||
|
||||
The HTTP client response methods now declare their callback parameters in the method signatures:
|
||||
|
||||
@boostsnippet('HTTP Client Throw Signatures', 'php')
|
||||
public function throw($callback = null);
|
||||
public function throwIf($condition, $callback = null);
|
||||
@endboostsnippet
|
||||
|
||||
If you override these methods in custom response classes, ensure your method signatures are compatible.
|
||||
|
||||
## Notifications
|
||||
|
||||
### Default Password Reset Subject
|
||||
|
||||
**Likelihood Of Impact: Very Low**
|
||||
|
||||
Laravel's default password reset mail subject has changed:
|
||||
|
||||
@boostsnippet('Password Reset Subject', 'text')
|
||||
// Laravel <= 12.x
|
||||
Reset Password Notification
|
||||
|
||||
// Laravel >= 13.x
|
||||
Reset your password
|
||||
@endboostsnippet
|
||||
|
||||
If your tests, assertions, or translation overrides depend on the previous default string, update them accordingly.
|
||||
|
||||
### Queued Notifications and Missing Models
|
||||
|
||||
**Likelihood Of Impact: Very Low**
|
||||
|
||||
Queued notifications now respect the `#[DeleteWhenMissingModels]` attribute and `$deleteWhenMissingModels` property defined on the notification class.
|
||||
|
||||
In previous versions, missing models could still cause queued notification jobs to fail in cases where you expected them to be deleted.
|
||||
|
||||
## Queue
|
||||
|
||||
### `JobAttempted` Event Exception Payload
|
||||
|
||||
**Likelihood Of Impact: Low**
|
||||
|
||||
The `Illuminate\Queue\Events\JobAttempted` event now exposes the exception object (or `null`) via `$exception`, replacing the previous boolean `$exceptionOccurred` property:
|
||||
|
||||
@boostsnippet('JobAttempted Event', 'php')
|
||||
// Laravel <= 12.x
|
||||
$event->exceptionOccurred;
|
||||
|
||||
// Laravel >= 13.x
|
||||
$event->exception;
|
||||
@endboostsnippet
|
||||
|
||||
If you listen for this event, update your listener code accordingly.
|
||||
|
||||
### `QueueBusy` Event Property Rename
|
||||
|
||||
**Likelihood Of Impact: Low**
|
||||
|
||||
The `Illuminate\Queue\Events\QueueBusy` event property `$connection` has been renamed to `$connectionName` for consistency with other queue events.
|
||||
|
||||
If your listeners reference `$connection`, update them to `$connectionName`.
|
||||
|
||||
### `Queue` Contract Method Additions
|
||||
|
||||
**Likelihood Of Impact: Very Low**
|
||||
|
||||
The `Illuminate\Contracts\Queue\Queue` contract now includes queue size inspection methods that were previously only declared in docblocks.
|
||||
|
||||
If you maintain custom queue driver implementations of this contract, add implementations for:
|
||||
|
||||
- `pendingSize`
|
||||
- `delayedSize`
|
||||
- `reservedSize`
|
||||
- `creationTimeOfOldestPendingJob`
|
||||
|
||||
## Routing
|
||||
|
||||
### Domain Route Registration Precedence
|
||||
|
||||
**Likelihood Of Impact: Low**
|
||||
|
||||
Routes with an explicit domain are now prioritized before non-domain routes in route matching.
|
||||
|
||||
This allows catch-all subdomain routes to behave consistently even when non-domain routes are registered earlier. If your application relied on previous registration precedence between domain and non-domain routes, review route matching behavior.
|
||||
|
||||
## Scheduling
|
||||
|
||||
### `withScheduling` Registration Timing
|
||||
|
||||
**Likelihood Of Impact: Very Low**
|
||||
|
||||
Schedules registered via `ApplicationBuilder::withScheduling()` are now deferred until `Schedule` is resolved.
|
||||
|
||||
If your application relied on immediate schedule registration timing during bootstrap, you may need to adjust that logic.
|
||||
|
||||
## Security
|
||||
|
||||
### Request Forgery Protection
|
||||
|
||||
**Likelihood Of Impact: High**
|
||||
|
||||
Laravel's CSRF middleware has been renamed from `VerifyCsrfToken` to `PreventRequestForgery`, and now includes request-origin verification using the `Sec-Fetch-Site` header.
|
||||
|
||||
`VerifyCsrfToken` and `ValidateCsrfToken` remain as deprecated aliases, but direct references should be updated to `PreventRequestForgery`, especially when excluding middleware in tests or route definitions:
|
||||
|
||||
@boostsnippet('CSRF Middleware Rename', 'php')
|
||||
use Illuminate\Foundation\Http\Middleware\PreventRequestForgery;
|
||||
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken;
|
||||
|
||||
// Laravel <= 12.x
|
||||
->withoutMiddleware([VerifyCsrfToken::class]);
|
||||
|
||||
// Laravel >= 13.x
|
||||
->withoutMiddleware([PreventRequestForgery::class]);
|
||||
@endboostsnippet
|
||||
|
||||
The middleware configuration API now also provides `preventRequestForgery(...)`.
|
||||
|
||||
## Support
|
||||
|
||||
### Manager `extend` Callback Binding
|
||||
|
||||
**Likelihood Of Impact: Low**
|
||||
|
||||
Custom driver closures registered via manager `extend` methods are now bound to the manager instance.
|
||||
|
||||
If you previously relied on another bound object (such as a service provider instance) as `$this` inside these callbacks, you should move those values into closure captures using `use (...)`.
|
||||
|
||||
### `Str` Factories Reset Between Tests
|
||||
|
||||
**Likelihood Of Impact: Low**
|
||||
|
||||
Laravel now resets custom `Str` factories during test teardown.
|
||||
|
||||
If your tests depended on custom UUID / ULID / random string factories persisting between test methods, you should set them in each relevant test or setup hook.
|
||||
|
||||
### `Js::from` Uses Unescaped Unicode By Default
|
||||
|
||||
**Likelihood Of Impact: Very Low**
|
||||
|
||||
`Illuminate\Support\Js::from` now uses `JSON_UNESCAPED_UNICODE` by default.
|
||||
|
||||
If your tests or frontend output comparisons depended on escaped Unicode sequences (for example `\u00e8`), update your expectations.
|
||||
|
||||
## Views
|
||||
|
||||
### Pagination Bootstrap View Names
|
||||
|
||||
**Likelihood Of Impact: Low**
|
||||
|
||||
The internal pagination view names for Bootstrap 3 defaults are now explicit:
|
||||
|
||||
@boostsnippet('Pagination Views', 'text')
|
||||
// Laravel <= 12.x
|
||||
pagination::default
|
||||
pagination::simple-default
|
||||
|
||||
// Laravel >= 13.x
|
||||
pagination::bootstrap-3
|
||||
pagination::simple-bootstrap-3
|
||||
@endboostsnippet
|
||||
|
||||
## Getting help
|
||||
|
||||
If you encounter issues during the upgrade:
|
||||
|
||||
- Check the [upgrade guide](https://laravel.com/docs/13.x/upgrade) for the latest details
|
||||
- Review the [GitHub comparison](https://github.com/laravel/laravel/compare/12.x...13.x) for skeleton changes
|
||||
|
|
@ -1,80 +0,0 @@
|
|||
---
|
||||
name: wayfinder-development
|
||||
description: "Use this skill for Laravel Wayfinder which auto-generates typed functions for Laravel controllers and routes. ALWAYS use this skill when frontend code needs to call backend routes or controller actions. Trigger when: connecting any React/Vue/Svelte/Inertia frontend to Laravel controllers, routes, building end-to-end features with both frontend and backend, wiring up forms or links to backend endpoints, fixing route-related TypeScript errors, importing from @/actions or @/routes, or running wayfinder:generate. Use Wayfinder route functions instead of hardcoded URLs. Covers: wayfinder() vite plugin, .url()/.get()/.post()/.form(), query params, route model binding, tree-shaking. Do not use for backend-only task"
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
|
||||
# Wayfinder Development
|
||||
|
||||
## Documentation
|
||||
|
||||
Use `search-docs` for detailed Wayfinder patterns and documentation.
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### Generate Routes
|
||||
|
||||
Run after route changes if Vite plugin isn't installed:
|
||||
```bash
|
||||
php artisan wayfinder:generate --no-interaction
|
||||
```
|
||||
For form helpers, use `--with-form` flag:
|
||||
```bash
|
||||
php artisan wayfinder:generate --with-form --no-interaction
|
||||
```
|
||||
|
||||
### Import Patterns
|
||||
|
||||
<!-- Controller Action Imports -->
|
||||
```typescript
|
||||
// Named imports for tree-shaking (preferred)...
|
||||
import { show, store, update } from '@/actions/App/Http/Controllers/PostController'
|
||||
|
||||
// Named route imports...
|
||||
import { show as postShow } from '@/routes/post'
|
||||
```
|
||||
|
||||
### Common Methods
|
||||
|
||||
<!-- Wayfinder Methods -->
|
||||
```typescript
|
||||
// Get route object...
|
||||
show(1) // { url: "/posts/1", method: "get" }
|
||||
|
||||
// Get URL string...
|
||||
show.url(1) // "/posts/1"
|
||||
|
||||
// Specific HTTP methods...
|
||||
show.get(1)
|
||||
store.post()
|
||||
update.patch(1)
|
||||
destroy.delete(1)
|
||||
|
||||
// Form attributes for HTML forms...
|
||||
store.form() // { action: "/posts", method: "post" }
|
||||
|
||||
// Query parameters...
|
||||
show(1, { query: { page: 1 } }) // "/posts/1?page=1"
|
||||
```
|
||||
|
||||
## Wayfinder + Inertia
|
||||
|
||||
Use Wayfinder with the `<Form>` component:
|
||||
<!-- Wayfinder Form (Vue) -->
|
||||
```vue
|
||||
<Form v-bind="store.form()"><input name="title" /></Form>
|
||||
```
|
||||
|
||||
## Verification
|
||||
|
||||
1. Run `php artisan wayfinder:generate` to regenerate routes if Vite plugin isn't installed
|
||||
2. Check TypeScript imports resolve correctly
|
||||
3. Verify route URLs match expected paths
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
- Using default imports instead of named imports (breaks tree-shaking)
|
||||
- Forgetting to regenerate after route changes
|
||||
- Not using type-safe parameter objects for route model binding
|
||||
|
|
@ -1,7 +0,0 @@
|
|||
[mcp_servers.laravel-boost]
|
||||
command = "php"
|
||||
args = ["artisan", "boost:mcp"]
|
||||
|
||||
[mcp_servers.nightwatch]
|
||||
command = "npx"
|
||||
args = ["-y", "mcp-remote", "https://nightwatch.laravel.com/mcp"]
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
{
|
||||
"mcpServers": {
|
||||
"laravel-boost": {
|
||||
"command": "php",
|
||||
"args": [
|
||||
"artisan",
|
||||
"boost:mcp"
|
||||
]
|
||||
},
|
||||
"nightwatch": {
|
||||
"command": "npx",
|
||||
"args": [
|
||||
"-y",
|
||||
"mcp-remote",
|
||||
"https://nightwatch.laravel.com/mcp"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,56 +0,0 @@
|
|||
---
|
||||
description: Guidelines for writing clean, maintainable, and human-readable code. Apply these rules when writing or reviewing code to ensure consistency and quality.
|
||||
globs: ["**/*"]
|
||||
alwaysApply: false
|
||||
---
|
||||
# Clean Code Guidelines
|
||||
|
||||
## Constants Over Magic Numbers
|
||||
- Replace hard-coded values with named constants
|
||||
- Use descriptive constant names that explain the value's purpose
|
||||
- Keep constants at the top of the file or in a dedicated constants file
|
||||
|
||||
## Meaningful Names
|
||||
- Variables, functions, and classes should reveal their purpose
|
||||
- Names should explain why something exists and how it's used
|
||||
- Avoid abbreviations unless they're universally understood
|
||||
|
||||
## Smart Comments
|
||||
- Don't comment on what the code does - make the code self-documenting
|
||||
- Use comments to explain why something is done a certain way
|
||||
- Document APIs, complex algorithms, and non-obvious side effects
|
||||
|
||||
## Single Responsibility
|
||||
- Each function should do exactly one thing
|
||||
- Functions should be small and focused
|
||||
- If a function needs a comment to explain what it does, it should be split
|
||||
|
||||
## DRY (Don't Repeat Yourself)
|
||||
- Extract repeated code into reusable functions
|
||||
- Share common logic through proper abstraction
|
||||
- Maintain single sources of truth
|
||||
|
||||
## Clean Structure
|
||||
- Keep related code together
|
||||
- Organize code in a logical hierarchy
|
||||
- Use consistent file and folder naming conventions
|
||||
|
||||
## Encapsulation
|
||||
- Hide implementation details
|
||||
- Expose clear interfaces
|
||||
- Move nested conditionals into well-named functions
|
||||
|
||||
## Code Quality Maintenance
|
||||
- Refactor continuously
|
||||
- Fix technical debt early
|
||||
- Leave code cleaner than you found it
|
||||
|
||||
## Testing
|
||||
- Write tests before fixing bugs
|
||||
- Keep tests readable and maintainable
|
||||
- Test edge cases and error conditions
|
||||
|
||||
## Version Control
|
||||
- Write clear commit messages
|
||||
- Make small, focused commits
|
||||
- Use meaningful branch names
|
||||
|
|
@ -1,26 +0,0 @@
|
|||
---
|
||||
description: Pagination conventions — backend (Inertia scroll) and frontend (InfiniteScroll)
|
||||
globs: **/*.{php,vue,ts}
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# Pagination
|
||||
|
||||
- Always use normal pagination (`->paginate()`). NEVER use `->cursorPaginate()`.
|
||||
- All paginated lists must use Inertia's scroll pagination: `Inertia::scroll()` on the backend with `<InfiniteScroll>` on the frontend. NEVER use traditional page-based pagination with page links/buttons.
|
||||
|
||||
```php
|
||||
// GOOD — backend
|
||||
return Inertia::render('Posts/Index', [
|
||||
'posts' => Inertia::scroll(fn () => PostResource::collection(
|
||||
Post::query()->latest()->paginate(20)
|
||||
)),
|
||||
]);
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- GOOD — frontend -->
|
||||
<InfiniteScroll :data="posts">
|
||||
<PostCard v-for="post in posts.data" :key="post.id" :post="post" />
|
||||
</InfiniteScroll>
|
||||
```
|
||||
|
|
@ -1,33 +0,0 @@
|
|||
---
|
||||
description: Inertia.js v3 — pages, props, SSR, breaking changes, deferred props patterns
|
||||
globs: **/*.{vue,ts,php}
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# Inertia v3
|
||||
|
||||
Inertia creates fully client-side rendered SPAs without modern SPA complexity, leveraging existing server-side patterns.
|
||||
|
||||
- Components live in `resources/js/pages` (unless overridden in `vite.config.js`). Use `Inertia::render()` for server-side routing instead of Blade views.
|
||||
- ALWAYS use the `search-docs` Boost tool for version-specific Inertia documentation and updated code examples.
|
||||
- Activate the `inertia-vue-development` skill when working with Inertia Vue client-side patterns.
|
||||
|
||||
## v3 features
|
||||
|
||||
- Use all Inertia features from v1, v2, and v3. Check the documentation before making changes to ensure the correct approach.
|
||||
- New in v3: standalone HTTP requests (`useHttp` hook), optimistic updates with automatic rollback, layout props (`useLayoutProps` hook), instant visits, simplified SSR via `@inertiajs/vite` plugin, custom exception handling for error pages.
|
||||
- Carried over from v2: deferred props, infinite scroll, merging props, polling, prefetching, once props, flash data.
|
||||
|
||||
## Deferred props
|
||||
|
||||
When using deferred props, add an empty state with a pulsing or animated skeleton.
|
||||
|
||||
## Breaking changes from earlier versions
|
||||
|
||||
- Axios has been removed. Use the built-in XHR client with interceptors, or install Axios separately if needed.
|
||||
- `Inertia::lazy()` / `LazyProp` has been removed. Use `Inertia::optional()` instead.
|
||||
- Prop types (`Inertia::optional()`, `Inertia::defer()`, `Inertia::merge()`) work inside nested arrays with dot-notation paths.
|
||||
- SSR works automatically in Vite dev mode with `@inertiajs/vite` — no separate Node.js server needed during development.
|
||||
- Event renames: `invalid` is now `httpException`, `exception` is now `networkError`.
|
||||
- `router.cancel()` is replaced by `router.cancelAll()`.
|
||||
- The `future` configuration namespace has been removed — all v2 future options are now always enabled.
|
||||
|
|
@ -1,47 +0,0 @@
|
|||
---
|
||||
description: Laravel Boost MCP tools, search-docs usage, Artisan and Tinker conventions
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# Laravel Boost Tools
|
||||
|
||||
Laravel Boost is an MCP server with tools tuned for this application. Prefer Boost tools over manual shell/file alternatives.
|
||||
|
||||
## Tools to prefer
|
||||
|
||||
- `database-query` — run read-only queries against the database instead of writing raw SQL in tinker.
|
||||
- `database-schema` — inspect table structure before writing migrations or models.
|
||||
- `get-absolute-url` — resolve the correct scheme/domain/port for project URLs. Always use this before sharing a URL.
|
||||
- `browser-logs` — read browser logs, errors, exceptions. Only recent entries are useful.
|
||||
|
||||
## search-docs (IMPORTANT)
|
||||
|
||||
- Always call `search-docs` before making code changes. It returns version-specific docs for installed packages automatically.
|
||||
- Pass a `packages` array to scope results when you know which packages are relevant.
|
||||
- Use multiple broad, topic-based queries: `['rate limiting', 'routing rate limiting', 'routing']`.
|
||||
- Do not add package names to queries; package info is already shared. Use `test resource table`, not `filament 4 test resource table`.
|
||||
|
||||
### Query syntax
|
||||
|
||||
1. Words = auto-stemmed AND logic: `rate limit` matches both "rate" AND "limit".
|
||||
2. `"quoted phrases"` = exact position matching.
|
||||
3. Mix: `middleware "rate limit"`.
|
||||
4. OR logic: pass multiple queries — `queries=["authentication", "middleware"]`.
|
||||
|
||||
## Artisan
|
||||
|
||||
- Run commands directly: `php artisan route:list`. Discover with `php artisan list`, inspect with `php artisan [command] --help`.
|
||||
- Filter routes: `--method=GET`, `--name=users`, `--path=api`, `--except-vendor`, `--only-vendor`.
|
||||
- Read config with dot notation: `php artisan config:show app.name`. Or read files in `config/`.
|
||||
- Read environment variables directly from `.env`.
|
||||
|
||||
## Tinker
|
||||
|
||||
- Use single quotes around the snippet to prevent shell expansion: `php artisan tinker --execute 'Your::code();'`.
|
||||
- Use double quotes for PHP strings inside: `php artisan tinker --execute 'User::where("active", true)->count();'`.
|
||||
- Do not create models via tinker without user approval — prefer tests with factories.
|
||||
|
||||
## Herd
|
||||
|
||||
- Site is served by Laravel Herd at `https?://[kebab-case-project-dir].test`. Use `get-absolute-url` for valid URLs. Never run commands to serve the site.
|
||||
- Use the `herd` CLI for services, PHP versions and sites (`herd sites`, `herd services:start <service>`, `herd php:list`). `herd list` shows all commands.
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue