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.
Form Requests were introduced to simplify validation handling by moving it out of controllers into dedicated classes.
php artisan make:request
to create Form Requests.rules
method of the request.authorize
method to enforce access control.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.