Step 8 — Validation

Replace inline if (!$title) checks with declarative rules that run before your action body.

What you will learn

  • Attach #[Validated] to createAction
  • Return HTTP 422 for bad client input
Before you start
  • Step 7 — working createAction

Add attributes

use Pionia\Validations\Attributes\Validated;

#[Validated(rules: [
    'title' => 'required|string|min:3',
    'status' => 'in:open,done,archived',
])]
protected function createAction(Arrayable $data): ApiResponse
{
    $task = table('tasks')->save([
        'title' => $data->getString('title'),
        'status' => $data->getString('status', 'open'),
        'assignee' => $data->getString('assignee', 'alex@northwind.studio'),
    ]);

    return response(0, 'Task created', ['task' => $task]);
}

Remove the manual ValidationException block from Step 7 — the attribute handles it.

Test failure

curl -s -w "\nHTTP %{http_code}\n" -X POST http://127.0.0.1:8000/api/v1/ \
  -H "Content-Type: application/json" \
  -d '{"service":"task","action":"create","status":"open"}'

Expect HTTP 422 and a message about title.

Reference: Validation guide.

Common mistakes

  • 422 never fires — typo in attribute namespace or rules string.
  • Validating in both attribute and manual code — pick one style per action.