0
0
Laravelframework~3 mins

Why Form request classes in Laravel? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how to keep your code neat and error-free by moving validation out of controllers!

The Scenario

Imagine building a web form where users submit data, and you manually check each input for errors in your controller code.

You write many lines to validate data, handle mistakes, and keep your controller messy.

The Problem

Manual validation clutters your controller, making it hard to read and maintain.

It's easy to forget checks or repeat code, causing bugs and security risks.

Fixing or updating validation means hunting through scattered code.

The Solution

Form request classes let you move validation logic into a dedicated place.

This keeps controllers clean and validation reusable.

Laravel automatically runs these checks before your controller code, so you only handle valid data.

Before vs After
Before
public function store(Request $request) { if (!$request->has('email') || !filter_var($request->email, FILTER_VALIDATE_EMAIL)) { return back()->withErrors(['email' => 'Invalid email']); } // save data }
After
public function store(UserRequest $request) { // data is already validated here // save data }
What It Enables

You can write cleaner, safer, and more organized code that scales well as your app grows.

Real Life Example

When building a signup form, form request classes ensure emails, passwords, and names meet rules without cluttering your main logic.

Key Takeaways

Manual validation clutters and complicates controllers.

Form request classes centralize and automate validation.

This leads to cleaner, safer, and easier-to-maintain code.