Classes of validation Laravel

Asked

Viewed 429 times

0

Good morning!!

Use for a long time some validation classes (CPF, e-mail, CNPJ) at the moment I’m starting to migrate to Aravel there arose the doubt. Where I put these validation classes?

What do the good practices of the Laravel recommend? I put the classes in a certain directory and call it? (if yes which directory) Either I should put these methods in a controller or a middleware?

What Good Practice Recommends?

Thank you very much

  • Everything inside the folder \app is carried by autoload, if you want to import just create a folder, play there and then import where you need ... But you can create a custom Validator and use the logic of your classes: https://laravel.com/docs/5.7/validation#Manually-Creating-validators

2 answers

2


You can create a request class that will be responsible for this, how? Follow the Laravel documentation link: https://laravel.com/docs/5.7/validation#form-request-validation

Example:

In your controller you will have a method to create a new user.

public function createUser(UserRequest $request){
      // logica para criar o usuário
}

*Observation, instead of using the Request $request default, you create a class, which you modify as you wish, in it you pass the required error messages and fields.

How to create a class Request? use the Artisan command: php artisan make:request NomeDaRequest, by default it will be created in the folder request/ just search in your IDE that you will find.

Within this new Request class, you have 2 methods that you will use to send error messages from the fields and the fields called mandatory, they are the rules() and the messages(). The rules() it checks the mandatory fields and messages() displays the error messages.

public function messages(){
    return [
          'title.required' => 'A title is required',
          'body.required'  => 'A message is required',
    ];
}

public function rules(){
       return [
              'title' => 'required|unique:posts|max:255',
              'body' => 'required',
       ];
}

0

  • That I didn’t know, but I prefer to create a class. Mind me very well, even when I use regex

  • @Romulosousa, this post is a custom RULE... I also create classes for validation... What I posted above is so you can do this in the request: $Rule = ['Cpf' => 'required|Cpf']; You create the validation rule.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.