Validation

Validated Input

Retrieve the request data that underwent validation

$validated = $request->validated();

Or with safe(), which returns an instance of Illuminate\Support\ValidatedInput

$validated = $request->safe()->only(['name', 'email']);
$validated = $request->safe()->except(['name', 'email']);
$validated = $request->safe()->all();

#Iterate

foreach ($request->safe() as $key => $value) {
    //
}

#Access as an array

$validated = $request->safe();
$email = $validated['email'];

Optional Fields

You will often need to mark your "optional" request fields as nullable if you do not want the validator to consider null values as invalid

// publish\_at field may be either null or a valid date representation
$request->validate([
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
    'publish\_at' => 'nullable|date',
]);

Display Validation Errors

<!-- /resources/views/post/create.blade.php -->
<h1>Create Post</h1>
@if ($errors->any())
    <div class="alert alert-danger">
 <ul>
 @foreach ($errors->all() as $error)
 <li><!--swig13--></li>
 @endforeach
 </ul>
 </div>
@endif
<!-- Create Post Form -->

See: Validation Errors

Validate Passwords

Ensure passwords have an adequate level of complexity

$validatedData = $request->validate([
    'password' => ['required', 'confirmed', Password::min(8)],
]);

Password rule object allows you to easily customize the password complexity requirements

// Require at least 8 characters...
Password::min(8)
// Require at least one letter...
Password::min(8)->letters()
// Require at least one uppercase and one lowercase letter...
Password::min(8)->mixedCase()
// Require at least one number...
Password::min(8)->numbers()
// Require at least one symbol...
Password::min(8)->symbols()

Ensure a password has not been compromised in a public password data breach leak

Password::min(8)->uncompromised()

Uses the k-Anonymity model via the haveibeenpwned.com service without sacrificing the user's privacy or security

Methods can be chained

Password::min(8)
    ->letters()
    ->mixedCase()
    ->numbers()
    ->symbols()
    ->uncompromised()

Rules

Can also be passed as an array

$validatedData = $request->validate([
    'title' => ['required', 'unique:posts', 'max:255'],
    'body' => ['required'],
]);

#after:date

Field must be a value after a given date.

'start\_date' => 'required|date|after:tomorrow'

Instead of a date string, you may specify another field to compare against the date

'finish\_date' => 'required|date|after:start\_date'

See before:date

#after_or_equal:date

Field must be a value after or equal to the given date.
See after:date

#before:date

Field must be a value preceding the given date.
The name of another field may be supplied as the value of date.
See after:date

#alpha_num

Field must be entirely alpha-numeric characters

#boolean

Field must be able to be cast as a boolean.
Accepted input are true, false, 1, 0, "1", and "0"

#confirmed

Field must have a matching field of {field}_confirmation.
For example, if the field is password, a matching password_confirmation field must be present

#current_password

Field must match the authenticated user's password.

#date

Field must be a valid, non-relative date according to the strtotime PHP function.

#email

Field must be formatted as an email address.

#file

Field must be a successfully uploaded file.
See: Uploaded Files

#max:value

Field must be less than or equal to a maximum value.
Strings, numerics, arrays, and files are evaluated like the size rule.

#min:value

Field must have a minimum value.
Strings, numerics, arrays, and files are evaluated like the size rule.

#mimetypes:text/plain,…

File must match one of the given MIME types:

'video' => 'mimetypes:video/avi,video/mpeg,video/quicktime'

File's contents will be read and the framework will attempt to guess the MIME type, regardless of the client's provided MIME type.

#mimes:foo,bar,…

Field must have a MIME type corresponding to one of the listed extensions.

'photo' => 'mimes:jpg,bmp,png'

File's contents will be read and the framework will attempt to guess the MIME type, regardless of the client's provided MIME type. Full listing of MIME types & extensions

#nullable

Field may be null.

#numeric

Field must be numeric.

#password

Field must match the authenticated user's password.

#prohibited

Field must be empty or not present.

#prohibited_if:anotherfield,value,…

Field must be empty or not present if the anotherfield field is equal to any value.

#prohibited_unless:anotherfield,value,…

Field must be empty or not present unless the anotherfield field is equal to any value.

#required

Field must be present in the input data and not empty.
A field is considered "empty" if one of the following conditions are true:

  • The value is null.
  • The value is an empty string.
  • The value is an empty array or empty Countable object.
  • The value is an uploaded file with no path.

#required_with:foo,bar,…

Field must be present and not empty, only if any of the other specified fields are present and not empty

#size:value

Field must have a size matching the given value.

  • For strings: number of characters
  • For numeric data: integer value (must also have the numeric or integer rule).
  • For arrays: count of the array
  • For files: file size in kilobytes
// Validate that a string is exactly 12 characters long...
'title' => 'size:12';
// Validate that a provided integer equals 10...
'seats' => 'integer|size:10';
// Validate that an array has exactly 5 elements...
'tags' => 'array|size:5';
// Validate that an uploaded file is exactly 512 kilobytes...
'image' => 'file|size:512';

#unique:table,column

Field must not exist within the given database table

#url

Field must be a valid URL See all available rules

Logic

// in routes/web.php
Route::get('/post/create', [App\Http\Controllers\PostController::class, 'create']);
Route::post('/post', [App\Http\Controllers\PostController::class, 'store']);
// in app/Http/Controllers/PostController...
public function store(Request $request)
{
    $validated = $request->validate([
        // input name => validation rules
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);
    // The blog post is valid...
}
Comments