3
I’m trying to search the net how I solve this and it’s taking a long time, it seems to be something simple but I’m breaking my head, I decided to create a post here.
I’m using Laravel 5.3 with Mysql in an environment provided by Laravel Homestead.
In a company registration form you have the CNPJ field that has a Mask that formats it (e.g.: 52,836,639/0001-05). This field is being stored in the database without formatting, only with the numbers (e.g. 52836639000105).It is a CHAR field(14).
Validation is being done by a Request (Empresarequest) with the following Ules
public function rules()
{
return [
'razao_social' => 'bail|required|max:128',
'nome_fantasia' => 'required',
'cnpj' => 'bail|required|unique:empresas|max:14'
];
}
But the unique
and the max:14
does not work because the data is coming formatted (with '.', '-' and '/') and in the database is not.
I’ve tried using an event to test a possible fix, but it’s still the same:
I put this in the boot of Appserviceprovider:
Empresa::saving(function ($empresa) {
$empresa->cnpj = 12345678912345; // 14 characteres
});
The question is:
In this validation mode, there is a way to clear CNPJ formatting before going through validation?
How are you doing this formatting? Before you insert it in the BD? to transform "52.836.639/0001-05" into "52836639000105" as you do?
– Miguel
@Miguel, in the method
store
I’m making a simple replace$data['cnpj'] = str_replace(['-', '/', '.'], '', $data['cnpj']);
before theEmpresa::create($data);
– Lucas Martins