Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 67 ยท Validation, Sessions and Files

Validation

Validate Laravel requests with validate() and Validator::make, use common rules, nested and conditional rules, after hooks, error messages and validated data.

Every piece of data that arrives from outside your application is untrusted: form fields, query strings, JSON bodies, uploaded files. Before you store it or act on it, you must check that it has the shape you expect. Doing that by hand in every controller is repetitive and easy to get wrong, so Laravel ships a validation system. You describe the rules for each field, and Laravel checks them, collects the error messages and sends the user back to the form with their input preserved.

This lesson shows how validation works in a controller, how to read the rules, how to show errors, and how to handle nested data and conditions. The previous lesson on forms and CSRF covered the HTML side; the next one, form requests, moves the rules out of the controller. If you have not seen validation in plain PHP, form validation explains the concepts that Laravel automates.

Laravel code cannot run on this site, so the real framework code is read-only. The runnable examples are a small validator class written in plain PHP that mimics the behavior, so you can experiment with rules and error messages.

validate() in a controller

The shortest path is validate() on the request:

PHP
<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;

class PostController extends Controller
{
    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'title' => ['required', 'string', 'max:255'],
            'body' => ['required', 'string', 'min:20'],
            'status' => ['required', 'in:draft,published'],
        ]);

        $post = Post::create($validated);

        return redirect()->route('posts.show', $post);
    }
}

If every rule passes, validate() returns an array containing only the fields that have rules (so extra input never slips through) and the code carries on. If any rule fails, Laravel throws a ValidationException and handles it itself:

  • For a normal browser request it redirects back to the previous page, flashes the old input and the errors to the session, and the form shows them with old() and @error.
  • For a request that expects JSON (an API client or fetch with an Accept: application/json header) it returns status 422 with a JSON body.
flowchart TD
    R["Request reaches validate()"] --> C{"All rules pass?"}
    C -->|yes| V["Returns validated data<br/>controller continues"]
    C -->|no| X["ValidationException"]
    X --> J{"Expects JSON?"}
    J -->|no| B["Redirect back<br/>flash old input and errors"]
    J -->|yes| U["422 response<br/>message and errors"]

One call covers the happy path and both failure paths, so controllers stay short.

Rules can be written as a pipe string ('required|string|max:255') or as an array. The array form is easier to read and is required for rule objects and for rules whose parameters contain a pipe or comma, such as a regular expression.

Common rules

Rule Meaning
required Present and not empty
nullable May be null; other rules are skipped when it is
sometimes Validate only when the field is present in the input
string, integer, numeric, boolean, array Type checks
email, url, uuid, date, ip Format checks
min:n, max:n, between:a,b, size:n Length of a string, value of a number, items in an array, kilobytes of a file
in:a,b,c The value is one of the list
confirmed A matching field_confirmation field exists
unique:table,column No row in the table already has this value
exists:table,column A row with this value exists
same:other, different:other Compare with another field
regex:/pattern/ Matches a regular expression
file, image, mimes:jpg,png, max:2048 Uploaded file checks (see file uploads)

bail stops checking a field after its first failure, which helps when later rules would be expensive (like unique) or confusing. For passwords, use the rule object instead of a string: Password::min(8)->letters()->numbers().

Showing the errors

In a Blade view the $errors variable is always available. It is a message bag:

BLADE
@if ($errors->any())
    <ul>
        @foreach ($errors->all() as $message)
            <li>{{ $message }}</li>
        @endforeach
    </ul>
@endif

<input name="title" value="{{ old('title') }}">
@error('title')
    <p class="text-red-600">{{ $message }}</p>
@enderror

$errors->first('title') returns the first message for a field, $errors->get('title') returns all of them, and $errors->has('title') tests for any. A JSON response from a failed validation looks like this:

JSON
{
    "message": "The email field must be a valid email address. (and 1 more error)",
    "errors": {
        "email": ["The email field must be a valid email address."],
        "password": ["The password field must be at least 8 characters."]
    }
}

Building a validator by hand

Outside a request you create a validator yourself with Validator::make():

PHP
<?php

use Illuminate\Support\Facades\Validator;

$validator = Validator::make($data, [
    'email' => ['required', 'email'],
]);

if ($validator->fails()) {
    return back()->withErrors($validator)->withInput();
}

$validated = $validator->validated();

$validator->safe()->only(['email']) returns a subset of the validated input. If a page has two forms, use a named bag (validateWithBag('login', [...])) so their errors do not mix.

A validator you can run

The class below is a stand-in, not Laravel's validator. It supports a dozen rules, wildcard paths such as items.*.qty, bail, nullable, required_if, confirmed, after hooks and a validated() method that returns only the fields with rules. The message wording follows Laravel's English messages.

PHP A mini validator with nested rules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Read the result: unlisted never reaches validated(), items.*.qty was checked once per line, email would stop at its first failure because of bail, and the after hook added an error that no single rule could express. In Laravel you would write the same rules in the same shape, and the real validator supports far more rules and custom messages.

Nested and array data

Dot notation addresses nested input, and * matches every element of an array:

PHP
<?php

$request->validate([
    'user.name' => ['required', 'string'],
    'user.address.city' => ['required', 'string'],
    'tags' => ['array', 'max:5'],
    'tags.*' => ['string', 'distinct', 'max:30'],
    'items' => ['required', 'array', 'min:1'],
    'items.*.sku' => ['required', 'exists:products,sku'],
    'items.*.qty' => ['required', 'integer', 'min:1'],
]);

Error keys use the concrete index (items.2.qty), which lets a form highlight the exact line that failed. If a field name itself contains a dot, escape it with a backslash.

Conditional rules

Many rules depend on other fields. Laravel has a family of them:

PHP
<?php

use Illuminate\Validation\Rule;

$request->validate([
    'type' => ['required', 'in:personal,company'],
    'company_name' => ['required_if:type,company', 'max:100'],
    'vat_number' => [Rule::requiredIf(fn () => $request->type === 'company' && $request->country === 'DE')],
    'phone' => ['required_without:email', 'nullable', 'string'],
    'coupon' => ['exclude_if:type,company', 'nullable', 'string'],
    'notes' => ['sometimes', 'string', 'max:500'],
]);

required_if, required_unless, required_with, required_without and required_with_all cover most cases. exclude_if removes a field from the validated data. sometimes skips the field when it is absent, which is useful for partial updates. When you need arbitrary logic, a validator built by hand can add rules conditionally:

PHP
<?php

$validator = Validator::make($data, ['games' => 'required|integer']);

$validator->sometimes('reason', 'required|max:200', function ($input) {
    return $input->games >= 100;
});

After hooks

Some checks involve several fields or outside systems, such as "the end date must be later than the start date" or "this coupon is valid for this cart". Add them as after callbacks. They run after the normal rules, even if some failed, so check $validator->errors()->isNotEmpty() first if the hook depends on clean data:

PHP
<?php

$validator = Validator::make($request->all(), [
    'starts_at' => ['required', 'date'],
    'ends_at' => ['required', 'date'],
]);

$validator->after(function ($validator) use ($request) {
    if ($validator->errors()->isNotEmpty()) {
        return;
    }
    if ($request->date('ends_at')->lte($request->date('starts_at'))) {
        $validator->errors()->add('ends_at', 'The end must be later than the start.');
    }
});

Errors as a response

The second stand-in shows what Laravel does with a failed validation. A tiny validator feeds a handler that either redirects back with flashed data or returns the 422 JSON shape. Passwords are never flashed back to the form.

PHP Redirect back or 422 JSON

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The same input produces two different answers, but your controller code is identical. Laravel decides based on whether the request expects JSON. Notice also that the password is not in the flashed old input.

Common mistakes

  • Validating but then reading $request->all() instead of the validated data. Use $request->validated() (or the return value of validate()) so unvalidated fields never reach create().
  • Relying on client-side checks alone. Browser validation is a convenience; the server must always validate.
  • Forgetting nullable on optional fields, so an empty value fails a later rule like string.
  • Using a pipe string for a regex: rule that contains |. Use the array form.
  • Putting complex cross-field logic into one giant rule instead of an after hook.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does $request->validate([...]) return when all rules pass?

    It returns the validated data, limited to the keys named in the rules, so unexpected input never reaches your create() call.
  2. 2. What happens when validation fails on a normal browser request?

    Laravel throws a ValidationException and turns it into a redirect back. For requests that expect JSON it returns a 422 response instead.
  3. 3. What does the * in items.*.qty mean?

    The wildcard applies the rule to the qty key of every item, and errors are reported with the concrete index such as items.2.qty.
  4. 4. Which tool fits "the end date must be after the start date"?

    Cross-field checks fit in an after callback, which runs once the normal field rules have run.
  5. 5. Why use the bail rule?

    bail avoids piling up messages and avoids running expensive rules, such as database lookups, on input that is already invalid.

Summary

  • $request->validate() checks input, returns only validated fields, and handles failures automatically.
  • Failures redirect back with flashed errors and old input for browsers, and produce a 422 JSON response for API-style requests.
  • Rules are pipe strings or arrays; common ones are required, nullable, string, email, min, max, in, confirmed, unique and exists.
  • @error, $errors->first() and $errors->all() display messages; old() refills inputs.
  • Dot and * notation validate nested and array data.
  • Conditional rules (required_if, Rule::requiredIf, sometimes, exclude_if) and after hooks cover dependent fields.
  • Always use the validated data, never the raw request, when saving.

Next: Form Requests and Custom Rules