php 48 lines · 6 steps

How a Laravel FormRequest validates input

A StoreUserRequest centralizes authorization, normalization, validation rules, and clean output for creating a user.

Explained by highlit
1<?php
2 
3namespace App\Http\Requests;
4 
5use Illuminate\Foundation\Http\FormRequest;
6use Illuminate\Validation\Rules\Password;
7use Illuminate\Support\Str;
8 
9class StoreUserRequest extends FormRequest
10{
11 public function authorize(): bool
12 {
13 return true;
14 }
15 
16 public function rules(): array
17 {
18 return [
19 'name' => ['required', 'string', 'max:255'],
20 'email' => ['required', 'string', 'email:rfc,dns', 'max:255', 'unique:users,email'],
21 'password' => ['required', 'confirmed', Password::defaults()],
22 'terms' => ['accepted'],
23 ];
24 }
25 
26 public function messages(): array
27 {
28 return [
29 'terms.accepted' => 'You must accept the terms and conditions to continue.',
30 ];
31 }
32 
33 protected function prepareForValidation(): void
34 {
35 $this->merge([
36 'email' => Str::lower(trim((string) $this->input('email'))),
37 'name' => trim((string) $this->input('name')),
38 ]);
39 }
40 
41 public function validated($key = null, $default = null): mixed
42 {
43 $data = parent::validated();
44 unset($data['terms'], $data['password_confirmation']);
45 
46 return data_get($data, $key, $default);
47 }
48}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1FormRequest objects keep validation logic out of controllers, giving each endpoint a single source of truth for its rules.
  2. 2prepareForValidation lets you normalize raw input before rules run, so trimming and casing never cause false validation failures.
  3. 3Overriding validated() lets you strip helper fields like confirmations so only persistable data reaches your model.

Related explainers

Share this explainer

Here's the card — post it anywhere.

How a Laravel FormRequest validates input — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code