MCPInstall

laravel-validation-patterns

Best practices for Laravel validation including Form Requests, custom rules, conditional validation, and input sanitization.

Installs
100
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/iserter/laravel-claude-agents --skill laravel-validation-patterns
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads laravel-validation-patterns automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

Laravel Validation Patterns

Form Request Classes (Standard Approach)

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class StoreOrderRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()->can('create', Order::class);
    }

    public function rules(): array
    {
        return [
            'customer_id' => ['required', 'exists:customers,id'],
            'items' => ['required', 'array', 'min:1'],
            'items.*.product_id' => ['required', 'exists:products,id'],
            'items.*.quantity' => ['required', 'integer', 'min:1'],
            'notes' => ['nullable', 'string', 'max:500'],
        ];
    }

    public function messages(): array
    {
        return [
            'items.required' => 'At least one item is required.',
            'items.*.product_id.exists' => 'Product #:position does not exist.',
        ];
    }

    protected function prepareForValidation(): void
    {
        $this->merge([
            'notes' => strip_tags($this->notes),
            'email' => strtolower($this->email),
        ]);
    }

    public function after(): array
    {
        return [
            function (\Illuminate\Validation\Validator $validator) {
                if ($this->hasExceededOrderLimit()) {
                    $validator->errors()->add('items', 'You have exceeded the daily order limit.');
                }
            },
        ];
    }
}

Custom Rule Objects

<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;

class StrongPassword implements ValidationRule
{
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (! preg_match('/[A-Z]/', $value)) {
            $fail('The :attribute must contain at least one uppercase letter.');
        }

        if (! preg_match('/[0-9]/', $value)) {
            $fail('The :attribute must contain at least one number.');
        }
    }
}

// Usage in rules
'password' => ['required', 'string', 'min:8', new StrongPassword],

Conditional Validation

public function rules(): array
{
    return [
        'type' => ['required', Rule::in(['individual', 'company'])],

        // Required only when type is company
        'company_name' => ['required_if:type,company', 'string', 'max:255'],

        // Excluded when type is individual (not present in validated data)
        'tax_id' => ['exclude_if:type,individual', 'required', 'string'],

        // Dynamic conditional rule
        'billing_address' => [
            Rule::when($this->boolean('different_billing'), ['required', 'string']),
        ],

        // Conditional with sometimes (only validates if field is present)
        'coupon_code' => ['sometimes', 'string', 'exists:coupons,code'],
    ];
}

Array and Nested Validation

public function rules(): array
{
    return [
        'tags' => ['required', 'array', 'min:1', 'max:10'],
        'tags.*' => ['string', 'max:50'],

        'items' => ['required', 'array'],
        'items.*.name' => ['required', 'string'],
        'items.*.options' => ['sometimes', 'array'],
        'items.*.options.*.key' => ['required_with:items.*.options', 'string'],
    ];
}

Database Rules

public function rules(): array
{
    return [
        // Unique with ignore (for updates)
        'email' => [
            'required',
            'email',
            Rule::unique('users')->ignore($this->user()),
        ],

        // Unique with scoping
        'slug' => [
            'required',
            Rule::unique('posts')->where('tenant_id', $this->user()->tenant_id),
        ],

        // Exists with additional constraints
        'category_id' => [
            'required',
            Rule::exists('categories', 'id')->where('active', true),
        ],
    ];
}

Enum Validation

use App\Enums\OrderStatus;

public function rules(): array
{
    return [
        'status' => ['required', Rule::enum(OrderStatus::class)],

        // Only allow specific enum values
        'priority' => [
            'required',
            Rule::enum(Priority::class)->only([Priority::High, Priority::Critical]),
        ],
    ];
}

Working with Validated Data

// In controller
public function store(StoreOrderRequest $request)
{
    // ✅ Use validated data only
    $validated = $request->validated();

    // ✅ Use safe() for partial access
    $orderData = $request->safe()->only(['customer_id', 'notes']);
    $items = $request->safe()->except(['notes']);

    // ✅ Merge additional trusted data
    $order = Order::create(
        $request->safe()->merge(['user_id' => $request->user()->id])->all()
    );

    // ❌ Never use unvalidated input
    $order = Order::create($request->all());

    // ❌ Never bypass validation
    $order = Order::create($request->input());
}

Common Pitfalls

// ❌ Validating inline in controllers
public function store(Request $request)
{
    $request->validate(['title' => 'required']);
    // Hard to test, not reusable
}

// ✅ Use Form Request classes
public function store(StorePostRequest $request)
{
    Post::create($request->validated());
}

// ❌ Missing bail - continues validating after first failure
'email' => ['email', 'unique:users', 'dns_check'],

// ✅ Use bail to stop on first failure
'email' => ['bail', 'email', 'unique:users'],

// ❌ Using $request->all() instead of validated data
Order::create($request->all());

// ✅ Only validated and safe data
Order::create($request->validated());

Checklist

  • Validation logic lives in Form Request classes, not controllers
  • authorize() method properly checks permissions
  • Custom Rule objects used for reusable complex validation
  • prepareForValidation() sanitizes input before validation
  • after() used for cross-field or business logic validation
  • Array and nested fields validated with wildcard notation
  • Database rules use proper scoping and ignore patterns
  • Only validated/safe data used when creating or updating models
  • bail used where early termination is desired
  • Custom error messages provided for user-facing fields

FAQ

What does the laravel-validation-patterns skill do?

Best practices for Laravel validation including Form Requests, custom rules, conditional validation, and input sanitization.

How do I install laravel-validation-patterns?

Run npx skills add https://github.com/iserter/laravel-claude-agents --skill laravel-validation-patterns in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/laravel-validation-patterns/ (personal) or .claude/skills/laravel-validation-patterns/ (project).

Which AI agents can use laravel-validation-patterns?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is laravel-validation-patterns safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains laravel-validation-patterns?

It is published by iserter in iserter/laravel-claude-agents. It has 100 recorded installs.

More from iserter/laravel-claude-agents

View all →

eloquent-best-practices

iserter/laravel-claude-agents

Best practices for Laravel Eloquent ORM including query optimization, relationship management, and avoiding common pitfalls like N+1 queries.

laravel-tdd

iserter/laravel-claude-agents

Open the skill to read its SKILL.md instructions.

Backend & APIs378 installs

laravel-blade-component-patterns

iserter/laravel-claude-agents

Open the skill to read its SKILL.md instructions.

Backend & APIs116 installs

api-resource-patterns

iserter/laravel-claude-agents

Open the skill to read its SKILL.md instructions.

Backend & APIs110 installs

laravel-systematic-debugging

iserter/laravel-claude-agents

Systematic debugging process for Laravel applications - ensures root cause investigation before attempting fixes. Use for any Laravel issue (test failures, bugs, unexpected behavior, performance problems).

Backend & APIs102 installs

laravel-queue-patterns

iserter/laravel-claude-agents

Best practices for Laravel queues including job structure, batching, chaining, middleware, retry strategies, and error handling.

Backend & APIs96 installs

Popular backend & apis skills

View category →

find-skills

vercel-labs/skills

Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.

OfficialBackend & APIs4.1M installs

entra-app-registration

microsoft/azure-skills

Guides Microsoft Entra ID app registration, OAuth 2.0 authentication, and MSAL integration. USE FOR: create app registration, register Azure AD app, configure OAuth, set up authentication, add API permissions, generate service principal, MSAL example, console app auth, Entra ID setup, Azure AD authentication. DO NOT USE FOR: Key Vault secrets (use azure-keyvault-expiration-audit), general Azure resource security guidance.

OfficialBackend & APIs566.7K installs

This skill should be used when the user wants to "write agent code", "build an agent with ADK", "add a tool", "create a callback", "define an agent", "use state management" — in a project that needs ADK (Agent Development Kit) API patterns and code examples. It provides a quick reference for agent types, tool definitions, orchestration patterns, callbacks, state management, the graph Workflow API, and reference recipes to study. Do NOT use for scaffolding (use google-agents-cli-scaffold) or deployment (use google-agents-cli-deploy).

Backend & APIs514.8K installs

embedded-captions

heygen-com/hyperframes

Add captions or subtitles to an existing single-subject talking-head video without editing the footage. Use for plain verbatim captions, cinematic captions embedded behind the subject, VFX captions, “炸/特效/酷炫字幕,” or a named identity from the 35-style catalog. Route by visual identity, not by backend engine. The quiet anchor rail is the default; embed every word only when the user explicitly wants a fully cinematic treatment. The workflow runs locally end to end, including transcription and subject matting; split multi-shot footage before applying it.

Backend & APIs453.3K installs

entra-agent-id

microsoft/azure-skills

Provision Microsoft Entra Agent Identity Blueprints, BlueprintPrincipals, and per-instance Agent Identities via Microsoft Graph, and configure OAuth 2.0 token exchange (fmipath, OBO, cross-tenant) including the Microsoft Entra SDK for AgentID sidecar. USE FOR: Agent Identity Blueprint, BlueprintPrincipal, agent OAuth, fmipath token exchange, agent OBO, Workload Identity Federation for agents, polyglot agent auth, Microsoft.Identity.Web.AgentIdentities. DO NOT USE FOR: standard Entra app registration (use entra-app-registration), Microsoft Foundry agent authoring (use microsoft-foundry).

OfficialBackend & APIs336.6K installs

neon

neondatabase/agent-skills

Overview of Neon, a complete set of cloud backend primitives around Lakebase Postgres: Auth, Object Storage, Functions, the AI Gateway, and Realtime. Start here to choose Neon for undecided login, files, APIs, and LLM calls, set up the CLI or MCP server, and follow the branch-first workflow. Use when building an app or backend on Neon, or when "Neon" or "Lakebase Postgres" is mentioned. Child skill neon-postgres wins for an existing DATABASEURL, SQL, schema, inspect, or search. Child skill neon-auth wins for login, users, sessions, identity routing, and Managed Better Auth setup. Child skill neon-realtime wins for live queries in reactive apps and agents. Also use for object storage, S3, buckets, serverless functions, function triggers, cron, AI gateway, LLM calls, realtime, logs, Loki, Grafana, observability, postgres, database, backend, Claimable Neon, neon.new, or a no-signup database.

Backend & APIs237.1K installs