Never trust user input. Laravel makes validation short and readable.
validate() in a controller
$request->validate([...]) checks the input. If a rule fails, Laravel redirects back automatically with the errors and the old input. If all rules pass, it returns only the validated data.
Common rules
required,nullablestring,integer,numeric,booleanemail,url,datemin:3,max:255,between:1,10unique:users,email— value must not exist in the tableconfirmed— needs a matchingpassword_confirmationfieldimage,mimes:jpg,png,max:2048(KB) for uploads
Showing errors in Blade
@error('email') <span>{{ $message }}</span> @enderrorvalue="{{ old('email') }}"refills the field after a failed submit
Form Requests
For bigger forms, run php artisan make:request StorePostRequest, put the rules in its rules() method, and type-hint it in the controller. The controller stays clean.
Example
<?php
public function store(Request $request)
{
$data = $request->validate([
'name' => 'required|string|max:100',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:8|confirmed',
]);
// only runs if every rule passed
User::create($data);
return redirect('/login')->with('success', 'Account created');
}
/* Blade:
<input name="email" value="{{ old('email') }}">
@error('email')
<span class="text-danger">{{ $message }}</span>
@enderror */
If the email is already registered, the user is sent back to the form with "The email has already been taken." under the field and their other input still filled in.