Form Requests in Laravel are custom request classes that contain validation and permission logic. Delegating validation to Form Requests allows you to keep controllers clean and manageable.
Origin
Form Requests were created to simplify validation by transferring it from controllers to dedicated classes.
Why are Form Requests Used?
- Cleaner Controllers: separates validation logic from application logic.
- Reusable Logic: Validation rules are reusable across many actions.
- Custom Error Messages: You may easily create custom messages for validation errors.
Best Practices.
- Generate Requests with Artisan: To create Form Requests, run 'php artisan make:request'.
- Use Rules Method: Define validation rules using the request's 'rules' method.
- Handle Authorization in Form Requests: Use the 'authorize' function to implement access restriction.
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());
}
Start monitoring today
Websites will go down, and errors will happen. With Ranetrace, you are sure to catch any errors and performance issues the moment they happen.
Takes 1 minute to get started.
No credit card required. Cancel anytime.