Regex in CPF with Laravel

1

The system I'm servicing has CPFs registered in two ways, with and without punctuation, due to poor start-up that did not impose a standard. The problem is that the CPF can not be repeated, and when the user types a CPF with no punctuation, if it is already recorded with punctuation, it will indicate that it is a new CPF.

I think I should use regex to compare the two, but I do not know how to apply to the query. Here is the query:

$customer = Customer::where('cpf', $valor)->first();
    
asked by anonymous 03.03.2017 / 15:31

2 answers

3

The biggest solution would be to normalize all values in the column without formatting. The tentative way is to treat the comparison values in the same way or by removing the formatting.

You can write a query in MySQL with replace()

SELECT replace(replace('123.456.789-10', '.', ''), '-', '')

The complete solution should look something like:

$valor = str_replace(array('.', '-'), '', $valor);
$customer = Customer::where("REPLACE(REPLACE(cpf, '.', ''),'-', '')", $valor)->first();
    
03.03.2017 / 16:01
1

Can do with pure php:

$valor = str_replace(".", "", $valor);
$valor = str_replace("-", "", $valor);
$customer = Customer::where('cpf', $valor)->first();

I've taken the example link

See if it works.

    
03.03.2017 / 15:44