Organize Large Forms with Laravel Form Objects
Many Laravel controllers start small.
public function store(StoreUserRequest $request)
{
User::create($request->validated());
}
As new requirements arrive, more responsibilities are added:
- Upload avatar
- Resize image
- Send email
- Assign role
- Create profile
- Log activity
Soon your controller looks like this:
public function store(...)
{
...
...
...
}
Hundreds of lines long.
The Better Approach
Create a dedicated Form Object.
class RegisterUserForm
{
public function store(array $data): User{
// Upload files// Create user// Assign role// Send emailreturn $user;
}
}
Use It Inside the Controller
public function store(
StoreUserRequest $request,
RegisterUserForm $form
) {
$user = $form->store(
$request->validated()
);
return redirect()->route('users.index');
}
Why Use Form Objects?
They help you:
- Keep controllers thin
- Group related form logic
- Reuse complex workflows
- Improve testing
- Separate HTTP handling from business logic
When to Use Form Objects
Consider using them when a form involves:
- File uploads
- Multiple models
- Business rules
- External APIs
- Notifications
- Database transactions