Your Controller Is Doing The Wrong Job
Open your controller. Look for a store method.
Does it have 40 lines of code? Do you see a giant validation block, several if statements, business logic, and then a return statement?
Your controller is doing work it should not do.
A controller has one job. It receives a request, calls a service to solve the problem, and returns a response. It is the waiter, not the chef.
When you put validation and authorization inside a controller, it becomes a mess. You end up with 80 lines of code that no one wants to touch.
Laravel has a built-in solution: Form Requests.
A common bad pattern looks like this:
- Validating input data
- Checking user permissions
- Transforming data
- Running business logic
This breaks the Single Responsibility Principle. A class should have only one reason to change. A controller changes when the request flow changes. It should not change just because a validation rule changes.
Use this command to fix it: php artisan make:request StorePostRequest
This creates a dedicated file for your request logic. Move these three things into the Form Request:
- Authorization: Use the authorize() method to check permissions.
- Validation: Use the rules() method to define your data requirements.
- Data Preparation: Use prepareForValidation() to clean or format data before validation.
Now look at your controller again:
public function store(StorePostRequest $request) { $post = Post::create($request->validated()); return redirect()->route('posts.show', $post); }
The controller is now two lines long. It acts like a waiter again.
Laravel runs the authorization and validation automatically before the controller method even starts. If validation fails, the user gets an error immediately.
Follow these guidelines:
- Keep validation inline if it is short and used in only one place.
- Use a Form Request if the validation grows, repeats, or includes authorization.
- Do not put business logic in a Form Request. Use a Service layer for that.
Find your messiest controller today. Extract the validation into a Form Request. Watch it shrink.
What is the largest store method you have ever seen? Tell me in the comments.
Source: https://dev.to/denisgusto1/seu-controller-ta-fazendo-o-trabalho-do-form-request-e-ele-nao-devia-512o
