Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Utils Laravel Package

jansenfelipe/utils

jansenfelipe/utils is a Laravel/PHP utility package with Brazilian helpers for validating and formatting CPF/CNPJ documents, CEP postal codes, and phone numbers, simplifying common data-cleaning and validation tasks in applications.

Deep Wiki
Context7

Getting Started

Install via Composer — there is no service provider, no facade, no published config:

composer require jansenfelipe/utils

Everything is exposed as static methods on JansenFelipe\Utils\Utils. There is nothing to register in config/app.php and nothing to resolve from the container. The fastest first step is a php artisan tinker session:

use JansenFelipe\Utils\Utils;

Utils::onlyNumbers('123.456.789-00');      // '12345678900'
Utils::mask('###.###.###-##', '12345678900'); // '123.456.789-00'
Utils::formatCpf('12345678900');          // '123.456.789-00'
Utils::formatCnpj('12345678000100');      // '12.345.678/0001-00'
Utils::formatCep('12345678');             // '12345-678'
Utils::validateCpf('123.456.789-00');     // bool
Utils::validateCnpj('12.345.678/0001-00');// bool

The first real use case is almost always normalizing a CPF/CNPJ/CEP coming off a form before persisting it. Pair an onlyNumbers() call in the request layer with the matching validate*() check, and reserve the format*() methods for the presentation layer.

Implementation Patterns

Normalize on input, format on output. Store documents as plain digits (onlyNumbers) and format them only when rendering. This keeps indexing, searching, and equality checks sane.

// Form request / controller
$payload['document'] = Utils::onlyNumbers($request->input('document'));

Custom validation rule. Since the package only returns bool, wrap it as a Rule so it composes with the rest of Laravel's validation:

class CpfRule implements \Illuminate\Contracts\Validation\Rule
{
    public function passes($attribute, $value): bool
    {
        return Utils::validateCpf((string) $value);
    }
    public function message(): string
    {
        return 'The :attribute is not a valid CPF.';
    }
}

Eloquent accessors for display. Keep the raw column digit-only and format in the accessor:

public function getCpfAttribute($value)
{
    return $value ? Utils::formatCpf($value) : null;
}

Mutators for consistency. Apply onlyNumbers in a mutator so all writes are normalized, regardless of call site:

public function setCpfAttribute($value)
{
    $this->attributes['cpf'] = Utils::onlyNumbers($value);
}

Companion packages. This utility is the shared core for the author's cpf-gratis, cnpj-gratis, and cep-gratis packages. If you need remote validation or CEP lookup, install those alongside this one rather than reimplementing.

Masks for custom fields. Utils::mask() is generic — use it for phone numbers, CNH, PIS, or any fixed-shape string where you don't want to hand-roll preg_replace.

Gotchas and Tips

  • Static-only means untestable seams. You cannot mock Utils::validateCpf() in a unit test. If your domain relies heavily on these checks, wrap them in an injectable DocumentService or a Laravel Rule object so tests can fake the collaborator.
  • No container binding. There's no way to swap the implementation, decorate it, or extend it cleanly. Treat it as a leaf utility, not a core service.
  • Input type discipline. Pass string. Passing null, int, or an array into the validators/masks is undefined behavior in a simple utility class — cast explicitly ((string) $value) at the boundary.
  • onlyNumbers() is blind. It strips every non-digit. It will happily reduce "abc" to "", and it does not guarantee a length is valid. Always follow with validate*() or your own length check.
  • Mask placeholder is #. If you write a custom mask, ensure the placeholder count matches the input length, or you'll get partial output without an exception.
  • Validation ≠ sanitization. validateCpf and validateCnpj perform algorithm/length checks; they do not reject empty strings consistently across versions. Guard with required in your rule set.
  • New alphanumeric CNPJ. Brazil's CNPJ format is transitioning to alphanumeric characters. Verify your installed version of this package handles the new format, or add a guard and pin accordingly. Test with a known alphanumeric sample before relying on it.
  • Locale scope. Everything here is Brazil-specific. For international identifiers, reach for a different library — don't stretch mask() to fit.
  • Debugging tip. When a validation fails unexpectedly, dump(Utils::onlyNumbers($input)) first — most "bugs" here are leading/trailing whitespace or a formatted value being passed where a digit string was expected.
  • Version pinning. Given the 61-star, low-churn profile, pin the version in composer.json and review the changelog on minor bumps. There's no long-term API guarantee.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
shitoudev/permissionmanager
johannesclimacus/laravel-tui
hocvt/seotools
vitalybaev/sypexgeo
amphibee/themosis-ignition
gito-me/fast-excel
frankyso/laravel-ipaymu
geolize-studio/laravel-chile
boomerangui/chat
jinas/dhivatar
store-doc/laravel-storage-driver
plus-it/laravel-translation-manager
diephp/perhaps
diephp/telegraph
osmaviation/spreadsheet
microsoft/fluentui-system-icons
mmccook/php-json-canonicalization-scheme
middlewares/firewall
qubiqx/montapacking
nyoncode/laravel-package-console