Security & APIs · 8 min read · Intermediate
Validation, Form Requests & Error Handling
Keep controllers razor-thin by moving validation rules and authorization into dedicated Form Request classes.
What you'll learn
- Generate dedicated Form Requests with `php artisan make:request`
- Validate foreign keys with `exists:table,column` and unique values safely
- Return automatic 422 JSON errors for API clients and flash errors for Blade forms
Overview
Keep controllers razor-thin by moving validation rules and authorization into dedicated Form Request classes.
Code Example
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreEnrollmentRequest extends FormRequest {
public function authorize(): bool {
return $this->user() !== null;
}
public function rules(): array {
return [
'course_id' => ['required', 'integer', 'exists:courses,id'],
'full_name' => ['required', 'string', 'min:2', 'max:80'],
];
}
}
Key Takeaways
- Generate dedicated Form Requests with
php artisan make:request - Validate foreign keys with
exists:table,columnand unique values safely - Return automatic 422 JSON errors for API clients and flash errors for Blade forms
Quick Check
Check Your Understanding
Score: 0 / 1
1. What does Laravel automatically return to an `Accept: application/json` client when a Form Request fails validation?
Study Workspace
Finished this lesson?
Your progress is saved locally in your browser, no account needed.