Laravel validator vs requests

2.5k Views Asked by At

Hello,

I want to understand how to handle data validation with Laravel 5. I see that this can be done using or the validator, or the request files. The thing is that there are many points I didn't get.

  • What is the difference between using a request file for validation or the validator class ?
  • If I have validation conditions, and I want to use them only if the concerned field was submitted, how can I do that ? If I use the "required" keyword, it won't work because it will fail when the field is not submitted. If I don't use it, it will accept empty strings...

Thanks ahead !

2

There are 2 best solutions below

0
On BEST ANSWER

1. Theoretically there is no difference between Controller validation and Validation using FormRequest. Normally you should use FormRequest. This will keep your controller clean and Minimal. But some time it is sensible to use Validator within controller, e.g you know there is going to be just one field to validate, then it would be overkill to use FormRequest. So it is a matter of preferance.

2. You don't have to use 'required' if the field is not required. Other validation for that field will still run if that field is submitted. If not submitted nothing will happen.

  .......
  'money' => 'numeric',
  .......

Above Rule will make sure that money field is numeric only if it is submitted. If no submitted no validation error will be thrown.

I hope this helps.

0
On
  1. Request classes are the better way to validate requests, because they help to extract this functionality from the constructor method, which should be as clean as possible.
  2. Use 'sometimes' validator. http://laravel.com/docs/5.1/validation#conditionally-adding-rules