Logics Guru

Laravel Form Request Validation

A form request with rules, custom messages and prepared input.

php Laravel PHP
php
<?php

declare(strict_types=1);

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

final class StoreArticleRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()->can('create', Article::class);
    }

    public function rules(): array
    {
        return [
            'title' => ['required', 'string', 'max:190'],
            'slug' => ['nullable', 'string', 'regex:/^[a-z0-9-]+$/', Rule::unique('articles')],
            'body' => ['required', 'string', 'min:100'],
            'status' => ['required', Rule::in(['draft', 'published'])],
            'tags' => ['nullable', 'array', 'max:10'],
            'tags.*' => ['integer', 'exists:tags,id'],
        ];
    }

    public function messages(): array
    {
        return [
            'body.min' => 'Articles need at least 100 characters of body copy.',
        ];
    }

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

Plain text: https://logicsguru.com/snippets/laravel-form-request-validation/raw