Weave Code
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

Filament Cep Field Laravel Package

jeffersongoncalves/filament-cep-field

Filament CEP Field adds a Brazilian postal code (CEP) input to Filament forms with automatic 99999-999 formatting, validation, and address lookup via BrasilAPI/ViaCEP/AwesomeAPI. Includes Laravel model caching, invalidation, queue support, and full Brazilian states mapping.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require jeffersongoncalves/filament-cep-field
    php artisan vendor:publish --tag=cep-migrations
    php artisan migrate
    
  2. Basic Usage:

    use JeffersonGoncalves\Filament\CepField\Forms\Components\CepInput;
    
    CepInput::make('cep')
        ->required()
        ->label('CEP');
    
  3. First Use Case: Add the field to a Filament form (e.g., CreateUserForm or EditUserForm) to enable real-time CEP validation and address auto-fill.


Implementation Patterns

Common Workflows

  1. Basic CEP Field:

    CepInput::make('postal_code')
        ->required()
        ->label('Código Postal');
    
  2. Auto-Populating Address Fields:

    CepInput::make('cep')
        ->setStreetField('street')
        ->setNeighborhoodField('neighborhood')
        ->setCityField('city')
        ->setStateField('state');
    
  3. Custom Button Placement:

    CepInput::make('cep')
        ->setMode('prefix') // Places button before input
        ->setActionLabel('Consultar CEP');
    
  4. Error Handling:

    CepInput::make('cep')
        ->setErrorMessage('CEP inválido ou não encontrado.');
    

Integration Tips

  • Form Validation: The field automatically validates CEP format (e.g., 99999-999).
  • API Providers: Supports multiple CEP APIs (BrasilAPI, ViaCEP, AwesomeAPI). Configure the default provider in config/cep-field.php.
  • Caching: Uses Laravel’s model caching to reduce API calls. Cache invalidation is automatic.
  • Queue Jobs: Cache management runs asynchronously via Laravel queues.

Advanced Patterns

  1. Dynamic Field Mapping:

    $fields = ['street', 'neighborhood', 'city', 'state'];
    $mappedFields = collect($fields)->mapWithKeys(fn($field) => [$field => $field]);
    
    CepInput::make('cep')
        ->setStreetField($mappedFields['street'])
        ->setNeighborhoodField($mappedFields['neighborhood'])
        // ... other fields
    
  2. Conditional Field Population: Use Filament’s visible() or reactive() methods to show/hide address fields based on CEP input:

    TextInput::make('street')
        ->visible(fn($record) => $record->cep !== null)
        ->reactive();
    
  3. Custom API Responses: Override the default API response handling by extending the component:

    class CustomCepInput extends CepInput {
        protected function handleApiResponse($response) {
            // Custom logic for parsing API response
        }
    }
    

Gotchas and Tips

Pitfalls

  1. SSL Certificate Errors:

    • Ensure cacert.pem is configured in php.ini or set via Laravel HTTP client:
      Http::withOptions(['verify' => '/path/to/cacert.pem']);
      
    • Avoid disabling SSL verification ('verify' => false) in production.
  2. API Rate Limits:

    • Cache responses aggressively to avoid hitting API limits. The package supports Laravel’s model caching out of the box.
  3. Field Name Conflicts:

    • Ensure mapped fields (e.g., street, city) match the actual field names in your form/model to avoid silent failures.
  4. Filament Version Mismatch:

    • The package requires Filament 5.3+ (as of v3.0.2). Check compatibility in composer.json.

Debugging Tips

  1. API Requests:

    • Enable Laravel’s HTTP logging to inspect API calls:
      'debug' => env('CEP_DEBUG', false),
      
      in config/cep-field.php.
  2. Cache Issues:

    • Clear the cache if address fields aren’t updating:
      php artisan cache:clear
      php artisan config:clear
      
  3. Validation Errors:

    • Custom error messages may not display if the field’s dehydrateStateUsing or dehydrateState methods override validation logic.

Extension Points

  1. Custom API Providers:

    • Extend the CepServiceProvider to add support for additional APIs:
      $this->app->bind(CepService::class, function ($app) {
          return new CustomCepService(); // Your implementation
      });
      
  2. Override Default Behavior:

    • Publish the config and customize:
      php artisan vendor:publish --tag=cep-config
      
      Modify config/cep-field.php to change default API provider, cache settings, etc.
  3. Local Testing:

    • Mock API responses for testing:
      Http::fake([
          'https://brasilapi.com.br/api/cep/v1/*' => Http::response(['data' => [...]]),
      ]);
      

Performance Tips

  • Batch Processing: Use Laravel queues to defer cache invalidation for bulk operations.
  • Lazy Loading: Load address fields dynamically (e.g., via AJAX) if they’re rarely used.
  • Cache Tags: Tag cached CEP responses for invalidation:
    Cache::tags(['cep'])->put('cep_12345', $data, now()->addHours(1));
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor