Validation

Validate incoming request data with expressive rules.

Syntax$request->validate(['field' => 'required']);

Laravel makes validation easy with the validate() method on the request. You supply an array of rules; if validation fails, Laravel automatically redirects back with error messages.

Example

Example · php
public function store(Request $request)
{
    $validated = $request->validate([
        'title' => 'required|max:255',
        'email' => 'required|email',
    ]);

    Post::create($validated);
}

When to use it

  • A registration controller validates the incoming form data with $request->validate() to ensure the email is unique and the password meets minimum length before creating the user.
  • An API endpoint returns a JSON 422 error with field-by-field error messages automatically when validation fails, without any extra code in the controller.
  • A Form Request class encapsulates the validation rules and authorization check for a checkout form, keeping the controller method a single line.

More examples

Validate inside a controller

validate() throws a ValidationException on failure (redirects back with errors) or returns the validated data array on success.

Example · php
public function store(Request $request): RedirectResponse
{
    $validated = $request->validate([
        'name'     => ['required', 'string', 'max:255'],
        'email'    => ['required', 'email', 'unique:users,email'],
        'password' => ['required', 'min:8', 'confirmed'],
    ]);

    User::create($validated);
    return redirect()->route('dashboard');
}

Create a Form Request class

Generates app/Http/Requests/StorePostRequest.php with authorize() and rules() stubs ready to fill in.

Example · bash
php artisan make:request StorePostRequest

Form Request with rules and messages

Encapsulates authorization, validation rules, and custom error messages in one class, injected into the controller via type-hinting.

Example · php
class StorePostRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()->can('create-post');
    }

    public function rules(): array
    {
        return [
            'title' => ['required', 'string', 'max:200'],
            'body'  => ['required', 'string'],
            'tags'  => ['array', 'max:5'],
            'tags.*'=> ['string', 'exists:tags,slug'],
        ];
    }

    public function messages(): array
    {
        return [
            'title.required' => 'Every post needs a title.',
        ];
    }
}

Discussion

  • Be the first to comment on this lesson.