Well, as you want to display, then you have two options:
- Format the value before sending to view;
- Format the value in the view
using JS.
To format using PHP the code you have shown should already serve. But if you want, take a look at my implementation to apply mask to CPF, CNPJ and Phone (it is taken into account that the value only has numbers):
/**
* Formata uma string segundo a máscara de CPF
* caso o tamanho da string seja diferente de 11, a string será retornada sem formatação
* @param string $cpf
* @return string
*/
function cpf($cpf) {
if (! $cpf) {
return '';
}
if (strlen($cpf) == 11) {
return substr($cpf, 0, 3) . '.' . substr($cpf, 3, 3) . '.' . substr($cpf, 6, 3) . '-' . substr($cpf, 9);
}
return $cpf;
}
/**
* Formata uma string segundo a máscara de CNPJ
* caso o tamanho da string seja diferente de 14, a string será retornada sem formatação
* @param $cnpj
* @return string
*/
function cnpj($cnpj) {
if (! $cnpj) {
return '';
}
if (strlen($cnpj) == 14) {
return substr($cnpj, 0, 2) . '.' . substr($cnpj, 2, 3) . '.' . substr($cnpj, 5, 3) . '/' . substr($cnpj, 8, 4) . '-' . substr($cnpj, 12, 2);
}
return $cnpj;
}
/**
* Formata uma string segundo a máscara de telefone
* caso o tamanho da string seja diferente de 10 ou 11, a string será retornada sem formatação
* @param string $fone
* @return string
*/
function fone($fone) {
if (! $fone) {
return '';
}
if (strlen($fone) == 10) {
return '(' . substr($fone, 0, 2) . ')' . substr($fone, 2, 4) . '-' . substr($fone, 6);
}
if (strlen($fone) == 11) {
return '(' . substr($fone, 0, 2) . ')' . substr($fone, 2, 5) . '-' . substr($fone, 7);
}
return $fone;
}
If you prefer to use a JS library, I recommend Inputmaskjs: https://github.com/RobinHerbots/Inputmask
You put Cpf, cnpj or phone in an input and then call the library method to apply any mask. On the github link above there are a number of examples you can follow.
You do not save the data with the mask?
– Wallace Maxters
Actually, there is nothing specific about Laravel, but here on the site there are several questions about how to do in PHP
– Wallace Maxters
Simplest way to put mask in PHP
– Wallace Maxters
The function you refer to in the question is already excellent. Your problem is how to make it work on
Laravel
.– ShutUpMagda
This can be done easily in js here is a very cool library: jQuery Mask
– JuniorNunes
The easiest thing for your question would be to format with Javascript with the library https://igorescobar.github.io/jQuery-Mask-Plugin/
– Bruno Pulis