#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →

Using Request Classes for Form Validation

Calling validate() directly inside a controller works well for simple forms, but as validation rules grow more complex, keeping them inline can clutter the controller. Laravel solves this with Form Request classes, which move validation entirely into their own dedicated file.

What Is a Form Request?

A Form Request is a custom class that extends Laravel's base request class, generated through Artisan. Instead of validating manually inside a controller method, the request is simply type-hinted as a parameter, and Laravel runs the validation automatically before the method even executes.

Structuring a Form Request

Each Form Request defines two key pieces: an authorize() method that controls whether the current user is allowed to make this request, and a rules() method that returns the same kind of validation array used with validate().

MethodPurpose
rules()Defines the validation rules for the request
authorize()Determines if the user is permitted to make this request
messages()Optionally overrides default validation error messages
validated()Returns only the fields that passed validation, inside the controller

Why Use Form Requests

Form handling and validation round out the request-side of a Laravel application — but every one of those forms usually ends with data being saved somewhere. That brings us to how Laravel connects to and works with databases, starting with the connection layer itself.

Creating and Wiring a Form Request

Generate the class with Artisan. It is placed in app/Http/Requests.

php artisan make:request StorePostRequest

Fill in the two main methods. The example below lets only logged-in users create a post and checks the title, body and an optional category.

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StorePostRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user() !== null;
    }

    public function rules(): array
    {
        return [
            'title'       => ['required', 'string', 'max:120', 'unique:posts,title'],
            'body'        => ['required', 'string', 'min:20'],
            'category_id' => ['nullable', 'integer', 'exists:categories,id'],
        ];
    }

    public function messages(): array
    {
        return [
            'title.unique' => 'A post with this title already exists.',
        ];
    }
}

Then type-hint it in the controller. By the time the method body runs, the data is already valid.

public function store(StorePostRequest $request)
{
    $post = $request->user()->posts()->create($request->validated());
    return redirect()->route('posts.show', $post);
}

What Happens When Validation Fails

Laravel resolves the request from the service container, calls authorize(), then runs rules(). The flow then depends on the result:

  • If authorize() returns false, a 403 response is sent and the controller never runs.
  • If validation fails on a normal form, the user is redirected back with errors and old input, which Blade shows through $errors and old('title').
  • If the request expects JSON, such as an API call, Laravel returns a 422 response containing the error messages.

Handy Hooks for Real Forms

prepareForValidation() cleans input before rules run, for example turning a title into a slug or trimming a phone number.

protected function prepareForValidation(): void
{
    $this->merge(['slug' => \Illuminate\Support\Str::slug($this->title)]);
}

Update requests often need to ignore the current record in a unique rule, which Rule::unique('posts')->ignore($this->route('post')) handles. attributes() lets you rename fields in error messages, so "category_id" can appear as "category".

Inline $request->validate() is still perfectly fine for a tiny form with one or two fields. Move to a Form Request once rules grow, repeat across actions, or need authorization logic.

Common Mistakes

  • Leaving authorize() returning false after generating the class, then wondering why every request gets a 403. Return true if a policy or middleware already handles access.
  • Using $request->all() after validation, which passes unvalidated extra fields to the model. Prefer validated() or safe()->only([...]).
  • Putting business logic, such as saving records, inside the Form Request.
  • Forgetting that API clients must send an Accept: application/json header to receive JSON errors instead of a redirect.

Testing a Form Request

Feature tests can check validation without opening a browser. Post invalid data to the route and assert the errors, for example $this->post('/posts', ['title' => ''])->assertSessionHasErrors('title');. For an API route, use postJson() and assertJsonValidationErrors(['title']). Add one passing case as well, so you know valid input really reaches the controller and creates a record.

Ready to master Laravel Training Course?

Join Uncodemy's hands-on Laravel program and build real, production-ready applications.

Explore Course