Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 67 ยท Validation, Sessions and Files

Form Requests and Custom Rules

Move Laravel validation into form request classes: authorize, rules, prepareForValidation, messages, custom ValidationRule objects, Rule::unique, in and enum.

Calling $request->validate() in a controller is fine for a couple of fields. As forms grow, the rule list swallows the controller, the same rules get copied into the update method, and "who is allowed to do this?" ends up somewhere else entirely. A form request is a dedicated class that bundles authorization, input preparation, rules and messages for one action. You type-hint it in the controller method, and Laravel validates before your method runs.

In this lesson you will generate a form request, use its hooks, write your own rule objects, and use the built-in rule builders Rule::unique, Rule::in and Rule::enum. If you need a refresher on the basics, see Validation first.

Laravel code cannot run on this site, so the real framework code is read-only. The runnable examples are plain-PHP stand-ins for the form request lifecycle and for rule objects, including a unique rule on SQLite.

Creating a form request

Terminal
php artisan make:request StorePostRequest

This creates app/Http/Requests/StorePostRequest.php:

PHP
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Str;

class StorePostRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()?->can('create', \App\Models\Post::class) ?? false;
    }

    protected function prepareForValidation(): void
    {
        $this->merge([
            'slug' => Str::slug($this->input('title', '')),
        ]);
    }

    /** @return array<string, array<int, mixed>> */
    public function rules(): array
    {
        return [
            'title' => ['required', 'string', 'max:120'],
            'slug' => ['required', 'string', 'unique:posts,slug'],
            'body' => ['required', 'string', 'min:20'],
        ];
    }

    /** @return array<string, string> */
    public function messages(): array
    {
        return [
            'title.required' => 'Give your post a title.',
            'body.min' => 'Write at least :min characters.',
        ];
    }

    /** @return array<string, string> */
    public function attributes(): array
    {
        return ['body' => 'article text'];
    }
}

Using it takes one type hint:

PHP
<?php

use App\Http\Requests\StorePostRequest;

class PostController extends Controller
{
    public function store(StorePostRequest $request): RedirectResponse
    {
        // Here the request is already authorized and validated.
        $post = $request->user()->posts()->create($request->validated());

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

The service container builds the request object like any other dependency. Form requests are special in that Laravel runs their validation as part of resolving them, so a failure never enters your method.

flowchart TD
    A["Router calls the controller"] --> B["Container resolves StorePostRequest"]
    B --> C{"authorize() true?"}
    C -->|no| D["403 Forbidden"]
    C -->|yes| E["prepareForValidation()"]
    E --> F["rules() are checked"]
    F --> G{"Valid?"}
    G -->|no| H["Redirect back with errors<br/>or 422 JSON"]
    G -->|yes| I["Controller method runs<br/>validated() is available"]

Authorization comes first, then input cleanup, then rules. The controller only sees requests that passed all of it.

The hooks, one by one

  • authorize() returns true or false. A false produces a 403 response, before any validation runs, so unauthorized users cannot probe your rules. Return true if authorization happens elsewhere, for example in a policy or middleware. If the class has no authorize() method at all, Laravel treats the request as authorized.
  • prepareForValidation() adjusts the input before the rules run: trim values, build a slug, normalize a phone number. $this->merge([...]) adds or replaces fields.
  • rules() returns the same rule array you would pass to validate(). It may use $this->route('post'), $this->user() and other request data.
  • messages() overrides error text by field.rule key. attributes() renames fields in the default messages, so "The body field" becomes "The article text field".
  • passedValidation() runs after success, for last-minute changes to the data.
  • after() may return an array of callables that receive the validator, the same as the after hooks in the previous lesson. Use it for cross-field checks.

Inside the controller, $request->validated() returns only the validated fields, and $request->safe()->only(['title']) or ->except([...]) returns a subset.

Reusing rules for create and update

An update usually has the same rules as a create, with small differences such as "ignore the current record for uniqueness". Inside the request you can read the bound model from the route and branch:

PHP
<?php

use Illuminate\Validation\Rule;

public function rules(): array
{
    $post = $this->route('post'); // null when creating

    return [
        'title' => ['required', 'string', 'max:120'],
        'slug' => ['required', Rule::unique('posts', 'slug')->ignore($post)],
        'status' => ['required', Rule::enum(PostStatus::class)],
    ];
}

When $post is null, ignore() ignores nothing, and on update it skips the current row. Some teams prefer two classes (StorePostRequest, UpdatePostRequest) and extract shared rules to a trait. Either approach works; pick the one that keeps each class easy to read.

Rule objects

Strings cover the common checks. When you need your own, write a rule object:

Terminal
php artisan make:rule Uppercase
PHP
<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;

class Uppercase implements ValidationRule
{
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (strtoupper((string) $value) !== (string) $value) {
            $fail('The :attribute must be uppercase.');
        }
    }
}

Use it by instantiating it in the rule array: 'code' => ['required', new Uppercase]. The rule calls $fail() with a message to report a problem and does nothing when the value is fine. A rule object is a plain class, so it can take constructor arguments (a maximum, a list of banned words) and services through its constructor if you create it with app().

If the logic is used only once, an inline closure has the same shape:

PHP
<?php

'code' => ['required', function (string $attribute, mixed $value, Closure $fail) {
    if (strtoupper($value) !== $value) {
        $fail("The {$attribute} must be uppercase.");
    }
}],

Rules that need to see the other input can also implement DataAwareRule (and ValidatorAwareRule for the validator), whose setData() and setValidator() Laravel calls for you.

A note on empty values: a rule object does not run for an empty, absent field unless it is created as an implicit rule (for example with make:rule --implicit). That is why required normally comes first in the array.

A form request you can run

This stand-in is not Laravel; it reproduces the lifecycle in about a hundred lines: authorize, prepare, validate with strings, rule objects and closures, then custom messages and attribute names. Three requests show the three outcomes.

PHP A form request lifecycle with rule objects

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 guest is rejected by authorize() before any rule runs. In the second case, the empty title uses the custom message, abc fails the rule object, the body message uses the attribute name "article text", and the closure rule rejects the tag. Only in the last case does validated() return data, including the slug created in prepareForValidation().

Rule::unique, Rule::in and Rule::enum

The Illuminate\Validation\Rule class builds rules that need parameters. Fluent objects are less error-prone than strings with commas.

PHP
<?php

use Illuminate\Validation\Rule;

return [
    // No other user has this email, except the user being edited
    'email' => ['required', 'email', Rule::unique('users', 'email')->ignore($this->user)],

    // Limit uniqueness to a scope, for example one team
    'name' => [Rule::unique('projects')->where('team_id', $this->user()->team_id)],

    // One of a fixed list
    'role' => ['required', Rule::in(['admin', 'editor', 'viewer'])],

    // The value must be a valid case of a backed enum
    'status' => ['required', Rule::enum(PostStatus::class)],

    // The related row must exist
    'category_id' => ['required', Rule::exists('categories', 'id')],

    // Apply rules only under a condition
    'vat' => [Rule::when($this->type === 'company', ['required', 'string'], ['nullable'])],
];

Rule::unique(...)->ignore($model) is the standard answer to "my update form says the email is already taken", because without it the row being edited collides with itself. Pass the model (or its id). Never put raw user input into ignore() for a column name or table. Laravel binds values, but table and column names come from your code, not from the request.

The next example is a stand-in that mimics Rule::unique()->ignore(), Rule::in() and Rule::enum() over SQLite, so you can see the query logic behind the fluent API.

PHP unique, in and enum rule objects on SQLite

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.

Check the third and fourth lines: ignore(1) lets user 1 keep their own address, while user 2 still cannot take it. The email is passed as a bound parameter (?), the standard defense against SQL injection that you will see again in database basics.

Common mistakes

  • Returning false from authorize() by default. A freshly generated stub may return false, so check it and change it to a real check or true, otherwise every request returns 403.
  • Forgetting ignore() in the update rules, so users cannot save their own record.
  • Reading $request->all() in the controller after using a form request. Use validated().
  • Putting heavy database queries inside prepareForValidation(). It runs on every request, including invalid ones.
  • Expecting a rule object to run on an empty field. Put required before it, or make the rule implicit.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when authorize() returns false?

    An unauthorized form request is rejected with 403 before the rules are checked.
  2. 2. Which method adjusts input, for example building a slug, before the rules run?

    prepareForValidation() runs first; use $this->merge() to add or replace fields. passedValidation() runs afterwards, only on success.
  3. 3. What does a ValidationRule object do to report a failure?

    validate() receives the attribute, the value and a $fail closure. Calling $fail('message') reports the error; doing nothing means the value is fine.
  4. 4. Why use Rule::unique('users', 'email')->ignore($user) on an update form?

    Without ignore(), the current row already holds the email, so the uniqueness check would fail on every save.
  5. 5. How does a controller get a validated form request?

    The container resolves the type-hinted FormRequest and runs its authorization and validation before the method is called.

Summary

  • A form request (make:request) groups authorization, input preparation, rules and messages for one action; type-hint it in the controller.
  • Order of events: authorize() (403 on false), prepareForValidation(), rules(), then the controller; validated() and safe() return the clean data.
  • messages() and attributes() customize the wording without touching the rules.
  • Rule objects (make:rule) implement ValidationRule::validate() and call $fail(); closures have the same signature.
  • Rule::unique()->ignore(), Rule::in(), Rule::enum(), Rule::exists() and Rule::when() build parameterized rules.
  • Put required before rule objects, since they skip empty values by default.

Next: Sessions, Flash Data and Cookies