L5-Repository Package Validators

Asked

Viewed 263 times

1

1º Is it possible to validate using the package itself? Currently, I use the package only to return the rules, example:

Validator::make($data, $this->getRules())->validate();

Onde:

$data:
São os meus dados que vieram do HTML.

$this->getRules()
Esse método getRules retornar minhas regras, é possível informar também se estou criando um dado ou atualizando ($action).

2º Is it possible to format the data before valid it?. When I did it by Form Request, I did it as follows, example:

public function validationData(){
     $data = $this->all();

     if(array_key_exists('valor_total', $data)){
         if (preg_match("/[,]/", $data['valor_total']) > 0){
            $data['valor_total'] = preg_replace('/[.]/', '', $data['valor_total']);
            $data['valor_total'] = preg_replace('/[,]/', '.', $data['valor_total']);
            $data['valor_total'] = (float)$data['valor_total'];
         }
     }

    $this->getInputSource()->replace($data);
    return $data;
}

3º It is possible to change a data after the validation. Example, I have a field called data_nascimento (date) that I receive from the front-end in d/m/Y format and in validation I check this same format, I want that after validation, format to Y-m-d. I know you can do it with mutators, but I’d like to do it with Validate.

4º How to perform Unique type validations? With Form Request, I would do it as follows:

public function rules(){
    $id = $this->route('filiai');

    return [
      'matriz_id' => 'required|integer|exists:pessoas_juridicas,id',
      'cnpj' => "required|cnpj|unique:empresas_filiais,cnpj,$id,id",
    ];
}

Only now with L5-Repository, I won’t have the request anymore, so how should I do it?.

5th Does anyone know any project (preferably with as many real examples as possible) in public repository to base me?

1 answer

1


First create the validation class:

Validator

Then register this validator in your repository:

inserir a descrição da imagem aqui

Now when you create the registry by repository or update, validators will automatically run.

$this->attributeRepository->create($data) $this->attributeRepository->update($data, $id)

If you need to manually execute:

inserir a descrição da imagem aqui

About Unique validation, it already identifies the Unique attribute you are creating or changing.

inserir a descrição da imagem aqui

About changing the data before entering into the database you can use the Mutators.

Browser other questions tagged

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