php 45 lines · 6 steps

How a Laravel FormRequest validates invoices

A FormRequest bundles authorization, validation rules, and localized error messaging into one reusable class.

Explained by highlit
1<?php
2 
3namespace App\Http\Requests;
4 
5use Illuminate\Foundation\Http\FormRequest;
6 
7class StoreInvoiceRequest extends FormRequest
8{
9 public function authorize(): bool
10 {
11 return $this->user()->can('create', Invoice::class);
12 }
13 
14 public function rules(): array
15 {
16 return [
17 'customer_email' => ['required', 'email', 'max:255'],
18 'issued_at' => ['required', 'date', 'before_or_equal:today'],
19 'due_at' => ['required', 'date', 'after:issued_at'],
20 'line_items' => ['required', 'array', 'min:1'],
21 'line_items.*.description' => ['required', 'string', 'max:500'],
22 'line_items.*.amount' => ['required', 'numeric', 'min:0.01'],
23 ];
24 }
25 
26 public function messages(): array
27 {
28 return [
29 'due_at.after' => __('validation.custom.invoice.due_after_issue'),
30 'line_items.min' => __('validation.custom.invoice.line_items_required'),
31 'line_items.*.amount.min' => __('validation.custom.invoice.positive_amount'),
32 ];
33 }
34 
35 public function attributes(): array
36 {
37 return [
38 'customer_email' => __('validation.attributes.customer_email'),
39 'issued_at' => __('validation.attributes.issued_at'),
40 'due_at' => __('validation.attributes.due_at'),
41 'line_items.*.description' => __('validation.attributes.line_item_description'),
42 'line_items.*.amount' => __('validation.attributes.line_item_amount'),
43 ];
44 }
45}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1FormRequest classes keep authorization and validation out of controllers so actions stay lean.
  2. 2Dot and star notation let you validate every element of a nested array with a single rule key.
  3. 3Overriding messages() and attributes() turns raw field names into human-friendly, translatable error text.

Related explainers

Share this explainer

Here's the card — post it anywhere.

How a Laravel FormRequest validates invoices — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code