Writing validation logic directly inside your controllers quickly bloats your code. When a single controller action contains 20 lines of validation rules, it becomes harder to test and maintain.

Laravel provides dedicated Form Request classes to extract validation rules into their own reusable classes.

Creating a Form Request

Generate a new request class using Artisan:

php artisan make:request StoreArticleRequest

Defining Rules and Authorization

Inside app/Http/Requests/StoreArticleRequest.php, define whether the user is authorized and what fields to validate:

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreArticleRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true; // Set to true or check auth permissions
    }

    public function rules(): array
    {
        return [
            'title' => ['required', 'string', 'max:255'],
            'category' => ['required', 'string'],
            'content' => ['required', 'string', 'min:50'],
        ];
    }
}

Type-Hinting in Your Controller

Simply replace the default Request with your new StoreArticleRequest. Laravel handles validation before the controller method even runs:

public function store(StoreArticleRequest $request)
{
    // If validation fails, Laravel redirects back automatically with errors.
    // At this point, the data is guaranteed to be valid!
    $validated = $request->validated();

    Article::create($validated);

    return redirect()->route('articles.index')->with('success', 'Article created!');
}

Customizing Error Messages

If you want friendly, custom error messages, add a messages() method:

public function messages(): array
{
    return [
        'content.min' => 'Please write at least 50 characters so your article is helpful.',
    ];
}

Why You Should Use Form Requests

  • Skinny Controllers: Your controller methods only care about business logic and responses.
  • Reusability: Use the same validation rules for API endpoints and web forms.
  • Automated Responses: Automatically returns HTTP 422 JSON for AJAX/API requests or redirects back with session errors for standard HTML forms.