php 42 lines · 6 steps

Normalizing input in a Laravel FormRequest

A FormRequest that authorizes, cleans, and validates article input before it reaches the controller.

Explained by highlit
1<?php
2 
3namespace App\Http\Requests;
4 
5use Illuminate\Foundation\Http\FormRequest;
6use Illuminate\Support\Str;
7use Illuminate\Validation\Rule;
8 
9class StoreArticleRequest extends FormRequest
10{
11 public function authorize(): bool
12 {
13 return $this->user()->can('create', Article::class);
14 }
15 
16 protected function prepareForValidation(): void
17 {
18 $this->merge([
19 'slug' => Str::slug($this->input('slug') ?: $this->input('title', '')),
20 'title' => trim($this->input('title', '')),
21 'tags' => collect(explode(',', (string) $this->input('tags')))
22 ->map(fn (string $tag) => Str::lower(trim($tag)))
23 ->filter()
24 ->unique()
25 ->values()
26 ->all(),
27 'published' => $this->boolean('published'),
28 ]);
29 }
30 
31 public function rules(): array
32 {
33 return [
34 'title' => ['required', 'string', 'max:150'],
35 'slug' => ['required', 'string', 'max:170', Rule::unique('articles', 'slug')],
36 'body' => ['required', 'string', 'min:50'],
37 'tags' => ['array', 'max:8'],
38 'tags.*' => ['string', 'max:30'],
39 'published' => ['boolean'],
40 ];
41 }
42}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1prepareForValidation lets you sanitize and reshape input before rules run, keeping controllers clean.
  2. 2Chaining collection methods turns messy comma-separated input into a deduplicated, trimmed array in one expression.
  3. 3Centralizing auth, normalization, and rules in one FormRequest keeps request concerns out of the controller.

Related explainers

Share this explainer

Here's the card — post it anywhere.

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