Form Requests

What are Form Requests?

Form Requests in Laravel are custom request classes designed to encapsulate validation and authorization logic. By delegating validation to Form Requests, you can keep controllers clean and maintainable.


Origin

Form Requests were introduced to simplify validation handling by moving it out of controllers into dedicated classes.


Why are they important?

  1. Cleaner Controllers: Keeps validation logic separate from application logic.
  2. Reusable Logic: Validation rules can be reused across multiple actions.
  3. Custom Error Messages: Easily define custom messages for validation errors.

Best Practices

  1. Generate Requests via Artisan: Use php artisan make:request to create Form Requests.
  2. Use Rules Method: Define validation rules in the rules method of the request.
  3. Handle Authorization in Form Requests: Implement the authorize method to enforce access control.

Example in Action

To validate a request for creating a post, generate a Form Request:

php artisan make:request StorePostRequest

In StorePostRequest, define validation rules:

public function rules()
{
    return [
        'title' => 'required|max:255',
        'content' => 'required',
    ];
}

In the controller, inject the request:

public function store(StorePostRequest $request)
{
    Post::create($request->validated());
}

This approach ensures validation is reusable and separated from the controller logic.