Form Requests
Validation is critical — you never trust user input. Laravel's Form Request classes let you pull validation logic out of controllers and into dedicated, testable classes. This keeps your controllers clean and your validation rules reusable.
Trust me, once you start using Form Requests, you'll never want to go back to inline validation.
Creating a Form Request
Generate a Form Request class with artisan:
php artisan make:request StorePostRequest
This creates a class in app/Http/Requests/StorePostRequest.php with two main methods:
class StorePostRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'title' => 'required|max:255',
'body' => 'required|min:10',
'category_id' => 'required|exists:categories,id',
];
}
}
The rules() method returns an array of validation rules. The authorize() method determines if the user is allowed to make this request.
Using Form Requests in Controllers
Type-hint the Form Request in your controller method. Laravel automatically validates before the method runs:
class PostController extends Controller
{
public function store(StorePostRequest $request)
{
$validated = $request->validated();
Post::create($validated);
return redirect('/posts');
}
}
If validation fails, the user is automatically redirected back with error messages. You don't need to write any if-statements.
Custom Messages and Hooks
You can customize validation messages by overriding the messages() method:
public function messages()
{
return [
'title.required' => 'Please give your post a title.',
'body.min' => 'Your post needs at least 10 characters.',
];
}
Use prepareForValidation() to modify or add data before validation runs:
public function prepareForValidation()
{
$this->merge([
'slug' => Str::slug($this->title),
'user_id' => auth()->id(),
]);
}
This method merges new attributes into the request before validation. The slug is generated from the title, and the current user's ID is attached automatically.