EthicsComputerCourses
Join training +91 90532 10052

Validation & Form Requests

TALL Stack · Lesson 6 of 20 Intermediate 11 min read Updated

By the end of this lesson Meera can add and edit customers in ShopLedger through real forms. You will write a Form Request class that cleans and checks the input, a custom rule for Indian mobile numbers, a controller that saves only validated data, and a Blade form that shows errors clearly to every user, including screen reader users.

What you should know first: Validation & Form Requests in the Laravel course explains the rule syntax, and Native HTML Form Validation explains required, maxlength and pattern. You also need ShopLedger from Eloquent Models & Migrations. All output below is from our app on Laravel 13.42.

Two checks, one judge

Think of a train journey from Indore. The ticket window checks your form before printing the ticket: wrong date, no name, try again. Then the TTE on the train checks the ticket again, because anyone can print something that looks like a ticket. The window is fast and friendly. The TTE is the one who really decides.

A web form works the same way:

CheckWhere it runsJob
HTML attributes (required, maxlength)The browserQuick hints before anything is sent
Laravel validationThe serverThe real decision, every time

The browser check is only a convenience. Anyone can switch it off in the browser tools or send a request with curl. So every rule must exist on the server. The browser copy is optional.

Step 1: routes for the forms

Add four routes inside the auth group in routes/web.php. Keep customers/create above customers/{customer}:

PHP
Route::get('customers', [CustomerController::class, 'index'])->name('customers.index');
Route::get('customers/create', [CustomerController::class, 'create'])->name('customers.create');
Route::post('customers', [CustomerController::class, 'store'])->name('customers.store');
Route::get('customers/{customer}', [CustomerController::class, 'show'])->name('customers.show');
Route::get('customers/{customer}/edit', [CustomerController::class, 'edit'])->name('customers.edit');
Route::put('customers/{customer}', [CustomerController::class, 'update'])->name('customers.update');

Order matters. Routes are checked from top to bottom. When we moved create below {customer}, the URL /customers/create returned 404: Laravel treated "create" as a customer id and found no such row.

Terminal
php artisan route:list --path=customers
Output
GET|HEAD customers .. customers.index › CustomerController@index
POST customers .. customers.store › CustomerController@store
GET|HEAD customers/create .. customers.create › CustomerController@create
GET|HEAD customers/{customer} .. customers.show › CustomerController@show
PUT customers/{customer} .. customers.update › CustomerController@update
GET|HEAD customers/{customer}/edit .. customers.edit › CustomerController@edit

Showing [6] routes

Before writing more, decide the areas Meera delivers to. Add them to config/shop.php, so the form and the rules read one list:

PHP
// The areas Meera delivers to. Forms offer only these.
'areas' => ['Bhawarkuan', 'Palasia', 'Rajwada', 'Sapna Sangeeta', 'Sudama Nagar', 'Vijay Nagar'],

Step 2: a custom rule for mobile numbers

Laravel has no rule for "Indian mobile number". A custom rule is a small class you write once and reuse in every form, including the Livewire forms later in this course.

Terminal
php artisan make:rule IndianMobile
Output
INFO Rule [C:\...\shopledger\app\Rules\IndianMobile.php] created successfully.

Fill in app/Rules/IndianMobile.php:

PHP
<?php

declare(strict_types=1);

namespace App\Rules;

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

class IndianMobile implements ValidationRule
{
    /**
     * An Indian mobile number has 10 digits and starts with 6, 7, 8 or 9.
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (! is_string($value) || preg_match('/^[6-9][0-9]{9}$/', $value) !== 1) {
            $fail('The :attribute must be a 10-digit Indian mobile number.');
        }
    }
}

$fail() records an error. Laravel replaces :attribute with the field's friendly name. The is_string() check matters: a tampered request can send phone[]=..., an array, and the rule must reject it instead of crashing.

Step 3: the Form Request

A Form Request is a class that holds everything about one form's input: who may send it, how to clean it, and which rules apply. The controller stays short, and the same rules are used for both "add" and "edit".

Terminal
php artisan make:request CustomerRequest
PHP
<?php

declare(strict_types=1);

namespace App\Http\Requests;

use App\Models\Customer;
use App\Rules\IndianMobile;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class CustomerRequest extends FormRequest
{
    public function authorize(): bool
    {
        // Any signed-in staff member, for now. The Authentication lesson adds a policy.
        return true;
    }

    /**
     * Clean the input before the rules run.
     */
    protected function prepareForValidation(): void
    {
        $phone = $this->input('phone');

        if (is_string($phone)) {
            // "+91 90000-00001" and "090000 00001" both become "9000000001".
            $digits = (string) preg_replace('/\D/', '', $phone);
            $this->merge(['phone' => (string) preg_replace('/^(91|0)(?=\d{10}$)/', '', $digits)]);
        }
    }

    /**
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        $customer = $this->route('customer');

        return [
            'name' => ['required', 'string', 'min:2', 'max:100'],
            'phone' => [
                'required',
                new IndianMobile,
                Rule::unique('customers', 'phone')->ignore($customer instanceof Customer ? $customer->id : null),
            ],
            'area' => ['nullable', 'string', Rule::in(config()->array('shop.areas'))],
        ];
    }

    /**
     * @return array<string, string>
     */
    public function attributes(): array
    {
        return ['phone' => __('mobile number')];
    }

    /**
     * @return array<string, string>
     */
    public function messages(): array
    {
        return ['phone.unique' => __('Another customer already has this mobile number.')];
    }
}

Each method has one job:

  • authorize() answers "may this user send this form?". Returning false gives a 403 page. The next lesson replaces true with a real check.
  • prepareForValidation() runs first and normalises the input: it turns the many ways people type a number into one form. Without it, 9000000001 and +91 90000 00001 would both be saved, and the unique check would miss the duplicate.
  • rules() lists the rules. Rule::unique(...)->ignore(...) says "unique, except this customer's own row", so saving Aarav without changing his number does not fail. Rule::in() accepts only the areas from the config file.
  • attributes() and messages() make the errors read well for Meera.

We ran four inputs through this class (in a small script that builds the request and calls validateResolved()):

Output
1. name "", phone "12345", area "Mumbai"
   name:  The name field is required.
   phone: The mobile number must be a 10-digit Indian mobile number.
   area:  The selected area is invalid.
2. phone "+91 90000-00001" (Aarav's number)
   phone: Another customer already has this mobile number.
3. name "Isha Rathore", phone "+91 90000 54321", area "Palasia", id 1, created_at "2020-01-01"
   validated: name "Isha Rathore", phone "9000054321", area "Palasia"
4. phone sent as an array
   phone: The mobile number must be a 10-digit Indian mobile number.

(Output rearranged from var_export() into short lines.) Look at case 3. The extra id and created_at fields did not survive: validated() returns only the fields that have rules. And the phone came out clean.

Step 4: a short controller

Add four methods to CustomerController. Type-hinting CustomerRequest makes Laravel run all the checks before your method starts:

PHP
public function create(): View
{
    return view('customers.create', ['customer' => new Customer]);
}

public function store(CustomerRequest $request): RedirectResponse
{
    $customer = Customer::create($request->validated());

    return to_route('customers.show', $customer)
        ->with('status', __('Customer :name added.', ['name' => $customer->name]));
}

public function edit(Customer $customer): View
{
    return view('customers.edit', ['customer' => $customer]);
}

public function update(CustomerRequest $request, Customer $customer): RedirectResponse
{
    $customer->update($request->validated());

    return to_route('customers.show', $customer)->with('status', __('Customer details saved.'));
}

If validation fails, the method never runs. Always pass $request->validated() to create() and update(), never $request->all(). Even with #[Fillable] on the model, validated() is the safer habit: it contains only fields you wrote a rule for. The show page prints the status flash message with @session('status').

Step 5: show the errors in Blade

create.blade.php and edit.blade.php both include one partial, resources/views/customers/form.blade.php. Here is the start of it and one field (phone and area follow the same pattern):

HTML
@csrf

@if ($errors->any())
    <div role="alert" class="rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-800 dark:border-red-900 dark:bg-red-950 dark:text-red-200">
        {{ __('Please fix the :count marked fields.', ['count' => $errors->count()]) }}
    </div>
@endif

<div>
    <label for="name" class="block text-sm font-medium text-zinc-700 dark:text-zinc-300">{{ __('Name') }}</label>
    <input id="name" name="name" type="text" value="{{ old('name', $customer->name) }}" required maxlength="100"
           @error('name') aria-invalid="true" aria-describedby="name-error" @enderror
           class="mt-1 w-full rounded-lg border border-zinc-300 px-3 py-2 aria-invalid:border-red-500 dark:border-zinc-600 dark:bg-zinc-900">
    @error('name')
        <p id="name-error" class="mt-1 text-sm text-red-600 dark:text-red-400">{{ $message }}</p>
    @enderror
</div>
  • @csrf adds the hidden token. A POST without it got 419 from our app.
  • old('name', $customer->name) refills the field after a failed save. On the edit page the second argument shows the saved value.
  • @error('name') ... @enderror prints only when that field has an error, and $message holds the text.
  • aria-invalid and aria-describedby tell screen readers which field is wrong and read the message aloud. The Tailwind variant aria-invalid:border-red-500 turns the border red from the same attribute.
  • The edit form adds @method('PUT'), because HTML forms can only send GET and POST.

What happens on a failed save

We posted an empty name, phone 12345 and area Mumbai while logged in as Meera. A normal form post gets a redirect back to the form:

Output
HTTP/1.1 302 Found
Location: http://127.0.0.1:8461/customers/create

Laravel stores the errors and the old input in the session, and the form page reads them. This is the real HTML our app sent after that redirect (layout left out, token shortened):

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Add customer - ShopLedger</title>
  <script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4.3.3"></script>
</head>
<body class="bg-white p-6">
  <div class="mx-auto max-w-md space-y-6">
    <h1 class="text-2xl font-semibold text-zinc-900">Add customer</h1>
    <form method="POST" action="http://127.0.0.1:8461/customers" class="space-y-4">
      <input type="hidden" name="_token" value="CBMmnuXh..." autocomplete="off">
      <div role="alert" class="rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-800">
        Please fix the 3 marked fields.
      </div>
      <div>
        <label for="name" class="block text-sm font-medium text-zinc-700">Name</label>
        <input id="name" name="name" type="text" value="" required maxlength="100"
               aria-invalid="true" aria-describedby="name-error"
               class="mt-1 w-full rounded-lg border border-zinc-300 px-3 py-2 aria-invalid:border-red-500">
        <p id="name-error" class="mt-1 text-sm text-red-600">The name field is required.</p>
      </div>
      <div>
        <label for="phone" class="block text-sm font-medium text-zinc-700">Mobile number</label>
        <input id="phone" name="phone" type="tel" inputmode="numeric" value="12345" required maxlength="16"
               aria-invalid="true" aria-describedby="phone-error"
               class="mt-1 w-full rounded-lg border border-zinc-300 px-3 py-2 aria-invalid:border-red-500">
        <p id="phone-error" class="mt-1 text-sm text-red-600">The mobile number must be a 10-digit Indian mobile number.</p>
      </div>
      <div>
        <label for="area" class="block text-sm font-medium text-zinc-700">Area</label>
        <select id="area" name="area" aria-invalid="true" aria-describedby="area-error"
                class="mt-1 w-full rounded-lg border border-zinc-300 px-3 py-2 aria-invalid:border-red-500">
          <option value="">Choose an area</option>
          <option value="Bhawarkuan">Bhawarkuan</option>
          <option value="Palasia">Palasia</option>
          <option value="Rajwada">Rajwada</option>
          <option value="Sapna Sangeeta">Sapna Sangeeta</option>
          <option value="Sudama Nagar">Sudama Nagar</option>
          <option value="Vijay Nagar">Vijay Nagar</option>
        </select>
        <p id="area-error" class="mt-1 text-sm text-red-600">The selected area is invalid.</p>
      </div>
      <button type="submit" class="rounded-lg bg-zinc-900 px-4 py-2 text-sm font-medium text-white">Save customer</button>
    </form>
  </div>
</body>
</html>

Notice that 12345 came back in the phone box, but "Mumbai" did not appear in the list, because it is not an allowed option.

The same request with the header Accept: application/json gets JSON instead of a redirect. Livewire and JavaScript code receive errors in this shape:

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

{"message":"The name field is required. (and 2 more errors)","errors":{"name":["The name field is required."],"phone":["The mobile number must be a 10-digit Indian mobile number."],"area":["The selected area is invalid."]}}

Try it: the browser's quick checks

The browser half can be friendlier than the server's. This demo uses required, maxlength and a pattern that allows spaces and +91, with Tailwind's user-invalid: variant, which turns the border red only after the user has touched the field. Leave the phone as 12345 and press Save.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Browser checks on the customer form</title>
  <script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4.3.3"></script>
  <style>[x-cloak] { display: none; }</style>
</head>
<body class="bg-zinc-100 p-6 font-sans">
  <form class="mx-auto max-w-md space-y-4 rounded-xl bg-white p-5 shadow"
        x-data="{ sent: false }" @submit.prevent="sent = true">
    <h1 class="text-lg font-semibold">Add customer</h1>
    <div>
      <label for="name" class="block text-sm font-medium text-zinc-700">Name</label>
      <input id="name" name="name" required maxlength="100"
             class="mt-1 w-full rounded-lg border border-zinc-300 px-3 py-2 user-invalid:border-red-500 user-valid:border-emerald-500">
    </div>
    <div>
      <label for="phone" class="block text-sm font-medium text-zinc-700">Mobile number</label>
      <input id="phone" name="phone" type="tel" inputmode="numeric" required maxlength="16"
             pattern="(\+91|0)?[\s\-]*[6-9]([\s\-]*[0-9]){9}" aria-describedby="phone-hint"
             class="peer mt-1 w-full rounded-lg border border-zinc-300 px-3 py-2 user-invalid:border-red-500 user-valid:border-emerald-500">
      <p id="phone-hint" class="mt-1 text-xs text-zinc-500 peer-user-invalid:text-red-600">10 digits starting with 6, 7, 8 or 9. Spaces and +91 are fine.</p>
    </div>
    <button class="rounded-lg bg-zinc-900 px-4 py-2 text-sm font-medium text-white">Save customer</button>
    <p x-show="sent" x-cloak class="rounded bg-emerald-50 p-2 text-sm text-emerald-800">
      The browser is happy. In ShopLedger the server now checks everything again.
    </p>
  </form>
  <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.17.5/dist/cdn.min.js"></script>
</body>
</html>

The browser blocks the form and shows its own message. Now type +91 90000 54321 and press Save: the success line appears. The pattern repeats the server's rule, but the server never trusts it. In ShopLedger we left pattern out of the real form and kept only required and maxlength, so there is just one place where the exact rule lives.

Where Livewire fits

Livewire forms use the same rules, written as PHP attributes or a rules() method in the component, and run with $this->validate(). Errors appear through the same @error directive, often while the user is still typing. The IndianMobile rule from this lesson works there unchanged. Livewire Forms & Validation builds the order form that way.

Common mistakes

  • Saving $request->all(). Hidden extra fields reach the model. Save $request->validated().
  • Validating only in the browser. A curl request skips every HTML attribute.
  • A unique rule without ignore() on edit. Saving a customer with their own number fails with "already taken".
  • Checking the raw input. Normalise first in prepareForValidation(), or duplicates slip through.
  • Error text in colour only. Add the message text and aria-invalid, not just a red border.
  • Putting customers/create after customers/{customer}. The wildcard swallows it and you get 404.

Interview questions

1. What is a Form Request and why use one?

It is a class that extends FormRequest and holds a form's authorisation check, input preparation, rules and messages. Laravel resolves and validates it before the controller method runs, so the controller only handles valid data. One class can serve both create and update.

2. What happens when validation fails in a normal form post, and in a JSON request?

For a normal post, Laravel redirects back with a 302 and puts the errors and old input in the session for the form to show. When the request expects JSON, it returns status 422 with a message and an errors object keyed by field name.

3. How do you keep a unique rule from failing when a record is edited?

Use Rule::unique('customers', 'phone')->ignore($customer->id). It checks every other row but skips the one being updated, so an unchanged value passes.

4. Why is browser validation not enough?

The user controls the browser. HTML attributes and JavaScript checks can be removed or skipped by sending the request directly. They improve the experience; the server rules are the ones that protect the data.

Key points

  • The browser checks for convenience; the server decides, every time.
  • A Form Request holds authorize(), prepareForValidation(), rules(), attributes() and messages() for one form.
  • Write reusable custom rules with php artisan make:rule, and reject non-strings.
  • Normalise input before validating, and use Rule::unique()->ignore() on edit.
  • Save only $request->validated(); extra fields are dropped.
  • Show errors with @error, old(), aria-invalid and aria-describedby; failed JSON requests get a 422.

Exercise

Meera wants to add an order from a customer's page. Write app/Http/Requests/StoreOrderRequest.php with these rules: ordered_on is a required date that is not in the future; amount is required, between ₹1 and ₹50,000, with at most two decimal places; status must be one of the OrderStatus cases; note is optional, at most 200 characters. Then write the controller method storeOrder(StoreOrderRequest $request, Customer $customer) that saves the order safely.

Show solution
PHP
public function rules(): array
{
    return [
        'ordered_on' => ['required', 'date', 'before_or_equal:today'],
        'amount' => ['required', 'decimal:0,2', 'min:1', 'max:50000'],
        'status' => ['required', Rule::enum(OrderStatus::class)],
        'note' => ['nullable', 'string', 'max:200'],
    ];
}

// CustomerController
public function storeOrder(StoreOrderRequest $request, Customer $customer): RedirectResponse
{
    $customer->orders()->create($request->validated());

    return to_route('customers.show', $customer)->with('status', __('Order added.'));
}

We tested the rules with a future date, 99.999, the status payed and a 201-character note:

Output
ordered_on: The ordered on field must be a date before or equal to today.
amount: The amount field must have 0-2 decimal places.
status: The selected status is invalid.
note: The note field must not be greater than 200 characters.

Creating the order through $customer->orders() sets customer_id from the URL's customer, so no form field can move the order to another account.

Quick Quiz

1. Where should the rule "phone must be unique" be enforced?

2. What does $request->validated() return when the form also sent an id field?

3. Why does ShopLedger normalise the phone in prepareForValidation()?

4. A request with Accept: application/json fails validation. What status code comes back?

Learn TALL Stack with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call