Validation — Laravel

Validation checks incoming data before it's used. $request->validate([...]) checks input against rules separated by |: required (present and not empty)…

Form validation in plain PHP usually turns into a ladder of ifs: if (empty($_POST['title'])), then if (!is_numeric($_POST['stock'])), then if (strlen($_POST['title']) > 255), each with its own error message. On the next form you write the ladder again.

Laravel turns that ladder into one list of rules. Validation checks incoming data before it's used: required fields are there, types are right, and values make sense. You only write the rules in $request->validate([...]). Laravel does the checking, the refusing and the error messages.

Picture the clerk who registers new books at the library. The clerk holds a list of requirements: the title must be there, the stock must be a number. An incomplete form is returned with a note next to each wrong field, and the book never reaches the shelf. The clerk is Laravel, the list of requirements is the rules in validate(), and the note next to a field is the error message for that field. Why the server must check input, and what status 422 (input that failed validation) means, are covered in the Input Validation lesson. Here we see how Laravel does it.

Rules for a new book

The Library app accepts new books through its API. Here's the route in routes/api.php. This file is created with php artisan install:api, and its addresses start with /api automatically:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::post('/books', function (Request $request) {
    $validated = $request->validate([
        'title' => 'required|string|max:255',
        'author' => 'required|string|max:255',
        'stock' => 'required|integer|min:0',
        'isbn' => 'nullable|string',
    ]);

    return response()->json($validated, 201);
});

Other rules you'll use often:

Rule Meaning
numeric a number, decimals allowed
email an email address format
in:novel,nonfiction must be one of the list
unique:books,isbn not yet in the isbn column of the books table

There is one problem with unique:books,isbn when a book is edited. The rule refuses the ISBN of the book being edited with The isbn has already been taken., because that ISBN is already in the table. So on a PUT /books/{book} route, tell the rule to skip this book's row with ignore($book):

use Illuminate\Validation\Rule;

'isbn' => ['nullable', 'string', Rule::unique('books', 'isbn')->ignore($book)],

Now saving the same ISBN passes, and another book's ISBN is still refused.

When it fails: 422 with message and errors

Send an empty body {} with the header Accept: application/json. This header tells the server that the client wants its answer as JSON. Laravel answers with this status line and these headers:

HTTP/1.1 422 Unprocessable Content
Content-Type: application/json

Then the body:

{
    "message": "The title field is required. (and 2 more errors)",
    "errors": {
        "title": ["The title field is required."],
        "author": ["The author field is required."],
        "stock": ["The stock field is required."]
    }
}

These are the answers to a few other bodies:

Body sent Status What's in errors
{} 422 title, author, stock: The ... field is required.
{"title": "The Dancer", "author": "Ahmad Tohari", "stock": -1} 422 stock: The stock field must be at least 0.
{"title": "The Dancer", "author": "Ahmad Tohari", "stock": -1.5} 422 stock: The stock field must be an integer. The stock field must be at least 0.
{"title": "The Dancer", "author": "Ahmad Tohari", "stock": 1} 201 (none)

When it passes: $validated

validate() returns only the fields that have rules. The body {"title": "The Dancer", "author": "Ahmad Tohari", "stock": 1, "is_admin": true} is answered 201 with {"title":"The Dancer","author":"Ahmad Tohari","stock":1}. is_admin is dropped, even though it was sent. That's why $validated is safe to pass to Book::create($validated). $request->all(), on the other hand, carries every field that was sent.

Before the check, all text goes through two built-in middleware. Middleware is code that processes a request before the request reaches your route. The first one cuts the spaces at the start and end of the text (TrimStrings). The second one turns empty text into null (ConvertEmptyStringsToNull). So "title": " " fails required, and "isbn": "" passes as null because its rule is nullable.

The Accept header: 422 or a redirect

Laravel picks the shape of its answer from the Accept header:

Request Answer when it fails
with Accept: application/json 422 with the message and errors JSON
without that header (a browser form) 302 redirect back to the previous page, errors kept in the session

The session is where Laravel keeps one visitor's data from one request to the next. For an HTML form, that redirect is what you need: the form page opens again, and Blade shows the message through @error('title') {{ $message }} @enderror. For an API client (a mobile app, or fetch in JavaScript), always send Accept: application/json. If you don't, that client only gets a redirect, for example to the app's main address http://localhost, not the error messages.

Form Request: rules in their own class

When the rules get long or are used in several places, move them into a Form Request, a special class that holds validation rules. Make the class with Artisan:

php artisan make:request StoreBookRequest

This is the class after the rules are written in the rules() method, and authorize() is changed to return true:

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreBookRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'title' => 'required|string|max:255',
            'author' => 'required|string|max:255',
            'stock' => 'required|integer|min:0',
            'isbn' => 'nullable|string',
        ];
    }
}

Then use that class in the route:

Route::post('/books', function (StoreBookRequest $request) {
    return response()->json($request->validated(), 201);
});

⚠️ Why a 302, a 403, or a different message?

TL;DR: Validation checks incoming data before it's used. $request->validate([...]) checks input against rules separated by |: required (present and not empty), string, integer, max:255 and min:0 (the number's value for a numeric field, the character count for text), and nullable (may be null). When something fails, the code below validate() never runs. Laravel answers 422 (input that failed validation) with message (the first message plus (and N more errors)) and errors for each field. This happens when the request carries the header Accept: application/json (asking for a JSON answer). Without that header, the answer is a 302 redirect. When it passes, the result, $validated, holds only the fields that have rules. Long rule sets move into a Form Request (a special class for validation rules, made with php artisan make:request StoreBookRequest). The authorize() method in that class (which decides who may send the request) must be changed to return true.

⚡ Rules in one list

Write:

$validated = $request->validate([
    'title' => 'required|string|max:255',
    'author' => 'required|string|max:255',
    'stock' => 'required|integer|min:0',
    'isbn' => 'nullable|string',
]);

Meaning: Validation checks incoming data before it's used. $request->validate([...]) takes a list of fields and their rules, and the rules for one field are separated by |. required means present and not empty, nullable means it may be null. max:255 and min:0 compare the number's value for a numeric field, and the character count for text. When everything passes, $validated holds the data.

⚡ When it fails, the code stops

Guess first: an empty body {} is sent with Accept: application/json. What does the client get?

Status 422 (input that failed validation) with the message "The title field is required. (and 2 more errors)" and errors for each field. The code below validate() never runs.

Meaning: Laravel refuses it by itself, so you don't write any if. The header Accept: application/json means the client asks for a JSON answer. Without that header, the answer is a 302 redirect back to the previous page.

In the exercise, the messages must be Laravel's exactly, for example The name field is required.

⚡ $validated holds only the fields with rules

Meaning: A field without rules, such as is_admin, is dropped from $validated, so $validated is safe to use in Book::create($validated). Long rule sets can move into a Form Request, a special class for validation rules (php artisan make:request StoreBookRequest). The condition: the authorize() method in that class (which decides who may send the request) must be changed to return true. While it's still false, every request is answered 403 (not allowed).

What you will learn