trypost/.cursor/skills/laravel-best-practices/rules/validation.md
Paulo Castellano 0c4acb04e8 refactor: update commands to use Sail and improve documentation
- Changed command from `php artisan` to `vendor/bin/sail artisan` in various documentation files to ensure consistency with the use of Laravel Sail.
- Updated `.mcp.json` to reflect the new command for Laravel Boost.
- Added new agent "cursor" in `boost.json` and enabled Sail support.
- Updated PHP version in `CLAUDE.md` from 8.4 to 8.5.
- Made minor adjustments to various skill documentation files to enhance clarity and ensure proper command usage.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-23 12:42:12 -03:00

1.7 KiB

Validation & Forms Best Practices

Use Form Request Classes

Extract validation from controllers into dedicated Form Request classes.

Incorrect:

public function store(Request $request)
{
    $request->validate([
        'title' => 'required|max:255',
        'body' => 'required',
    ]);
}

Correct:

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.

// 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:

Post::create($request->all());

Correct:

Post::create($request->validated());

Use Rule::when() for Conditional Validation

'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.

public function after(): array
{
    return [
        function (Validator $validator) {
            if ($this->quantity > Product::find($this->product_id)?->stock) {
                $validator->errors()->add('quantity', 'Not enough stock.');
            }
        },
    ];
}