Build a Laravel form from your validation rules
Turn a Form Request into a Blade form whose fields fill in old input and show their own errors, in a controller or a Livewire component.
php artisan bladewell:add text-input number select datepicker textarea checkbox file-upload button
Uses Text input, Number, Select, Date picker, Textarea, Checkbox, File upload and Button. New to Bladewell? Install it first.
Start from your rules
Your Form Request already says what every field is: its name, whether it's required, how long it can be, which values it takes. The form only has to say the same. Here's a booking with a few kinds of field:
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class StoreBookingRequest extends FormRequest
{
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:120'],
'email' => ['required', 'email'],
'guests' => ['required', 'integer', 'min:1', 'max:12'],
'room' => ['required', Rule::in(['standard', 'deluxe', 'suite'])],
'arrival' => ['required', 'date', 'after:today'],
'notes' => ['nullable', 'string', 'max:500'],
'newsletter' => ['boolean'],
'passport' => ['nullable', 'file', 'mimes:pdf,jpg,png', 'max:2048'],
];
}
}
Name each field after its rule
Give each component the rule's key as its name, then copy the limits across: max:120 becomes maxlength="120", in:… becomes a select's :options, mimes becomes the upload's accept. Add required where the rules say required, and leave it off for nullable.
<form method="POST" action="{{ route('bookings.store') }}" enctype="multipart/form-data" class="grid gap-5">
@csrf
<x-widget.text-input name="name" label="Name" maxlength="120" required />
<x-widget.text-input name="email" type="email" label="Email" required />
<x-widget.number name="guests" label="Guests" :decimals="0" :min="1" :max="12" required />
<x-widget.select name="room" label="Room" :options="['standard' => 'Standard', 'deluxe' => 'Deluxe', 'suite' => 'Suite']" required />
<x-widget.datepicker name="arrival" label="Arrival" :min="now()->addDay()->toDateString()" :max="false" required />
<x-widget.textarea name="notes" label="Notes" maxlength="500" counter />
<x-widget.checkbox name="newsletter" label="Send me offers" unchecked-value="0" />
<x-widget.file-upload name="passport" label="Passport scan" accept=".pdf,.jpg,.jpeg,.png" max-size="2048" />
<x-widget.button type="submit">Book</x-widget.button>
</form>
The browser now stops most mistakes before the form is sent, and your rules still decide on the server. A file field needs enctype="multipart/form-data" on the form. A boolean checkbox takes unchecked-value="0", so unticking it sends a value too.
The installation guide's table lists the component and props for every common rule, including the traps: mimes:jpg accepts .jpeg files too, and a date picker allows nothing after today until you pass :max="false".
The controller
Nothing in it is about the form. Type-hint the Form Request and Laravel validates before store runs.
namespace App\Http\Controllers;
use App\Http\Requests\StoreBookingRequest;
use App\Http\Requests\UpdateBookingRequest;
use App\Models\Booking;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Gate;
use Illuminate\View\View;
class BookingController extends Controller
{
public function create(): View
{
return view('bookings.create');
}
public function store(StoreBookingRequest $request): RedirectResponse
{
$booking = Booking::create([
...$request->safe()->except('passport'),
// On the local disk by name, which is private (storage/app/private): a passport scan must never get a public
// URL, even in an app whose default disk is public or S3.
'passport_path' => $request->file('passport')?->store('passports', 'local'),
]);
return redirect()->route('bookings.show', $booking);
}
public function edit(Booking $booking): View
{
// The same check as UpdateBookingRequest's: no one sees a booking they can't change.
Gate::authorize('update', $booking);
return view('bookings.edit', ['booking' => $booking]);
}
public function update(UpdateBookingRequest $request, Booking $booking): RedirectResponse
{
$booking->update($request->validated());
return redirect()->route('bookings.show', $booking);
}
}
Errors and old input, without a line of code
When validation fails, Laravel sends the visitor back with the errors and what they typed. Each component looks itself up by its name: it fills in the old value (except the file upload: browsers never let a page refill a file, so it's picked again), shows its own error under the field, marks itself aria-invalid and links the message with aria-describedby, so screen readers announce it. There's no @error block and no old() call to write.
The messages come from the default error bag. For a form that validates into a named bag, as with validateWithBag('booking', …), add bag="booking" to its fields.
The edit form
Pass the saved value as :value. After a failed submit, old input still wins, so the visitor sees what they typed, not what was saved. Date pickers take a date object as well as a Y-m-d string.
<form method="POST" action="{{ route('bookings.update', $booking) }}" class="grid gap-5">
@csrf
@method('PUT')
<x-widget.text-input name="name" label="Name" maxlength="120" :value="$booking->name" required />
<x-widget.number name="guests" label="Guests" :decimals="0" :min="1" :max="12" :value="$booking->guests" required />
{{-- From tomorrow, as for a new booking, unless the saved arrival is earlier: that one can stay as it is. --}}
<x-widget.datepicker name="arrival" label="Arrival" :min="$booking->arrival->min(now()->addDay())" :max="false" :value="$booking->arrival" required />
<x-widget.button type="submit">Save</x-widget.button>
</form>
An existing booking needs its own rules, and a check that the person may change it: authorize() asks your BookingPolicy, and the controller's edit does the same with Gate::authorize(). Requiring tomorrow or later, as for a new booking, would refuse every edit to a booking whose arrival has passed, even a new name. So the edit form starts the picker at its saved arrival when that's earlier, and the rules accept that date unchanged while any new date must still be from tomorrow. Cast arrival to date on the model for ->min() and ->toDateString().
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class UpdateBookingRequest extends FormRequest
{
// Only someone allowed to change this booking: the BookingPolicy's update(), e.g. its owner.
public function authorize(): bool
{
return $this->user()->can('update', $this->route('booking'));
}
public function rules(): array
{
// The booking being edited, from the route: Route::put('/bookings/{booking}', …).
$booking = $this->route('booking');
return [
'name' => ['required', 'string', 'max:120'],
'guests' => ['required', 'integer', 'min:1', 'max:12'],
'arrival' => [
'required',
'date_format:Y-m-d',
// A new date must be from tomorrow; the saved one may stay, even once it has passed.
Rule::when($this->input('arrival') !== $booking->arrival->toDateString(), ['after:today']),
],
];
}
}
In a Livewire component
Swap name for wire:model. The components read their errors from Livewire instead of the session, and fill in from the bound properties. They don't need Livewire, so the same component works in both kinds of form.
namespace App\Livewire;
use App\Models\Booking;
use Livewire\Component;
class BookingForm extends Component
{
public string $name = '';
public string $email = '';
public ?int $guests = null;
public function save()
{
$validated = $this->validate([
'name' => ['required', 'string', 'max:120'],
'email' => ['required', 'email'],
'guests' => ['required', 'integer', 'min:1', 'max:12'],
]);
$booking = Booking::create($validated);
return $this->redirectRoute('bookings.show', $booking);
}
public function render()
{
return view('livewire.booking-form');
}
}
The view is the same form, with wire:model in place of name, and wire:submit calling save():
<form wire:submit="save" class="grid gap-5">
<x-widget.text-input wire:model="name" label="Name" maxlength="120" required />
<x-widget.text-input wire:model="email" type="email" label="Email" required />
<x-widget.number wire:model="guests" label="Guests" :decimals="0" :min="1" :max="12" required />
<x-widget.button type="submit">Book</x-widget.button>
</form>